/*
 * @Author: your name
 * @Date: 2024-05-27
 * @LastEditTime: 2025-04-10
 * @LastEditors: 
 * @Description: In User Settings Edit
 * @FilePath: \src\api\dmgis.js
 */
import projzh from 'projzh';

import axios from 'axios';

import TileLayer from 'ol/layer/Tile';
import ImageLayer from 'ol/layer/Image';
import VectorLayer from 'ol/layer/Vector';
import XYZ from 'ol/source/XYZ';
import OSM from 'ol/source/OSM';
import VectorSource from 'ol/source/Vector';
import TileImage from 'ol/source/TileImage';
import ImageStatic from 'ol/source/ImageStatic';
import { get as getProjection } from 'ol/proj';
import { transform } from 'ol/proj';
import { Projection, addProjection, addCoordinateTransforms } from 'ol/proj';
import { transformExtent } from 'ol/proj'; //from 'ol/proj/transformExtent';
import TileGrid from 'ol/tilegrid/TileGrid';
import { applyTransform } from 'ol/extent';
import Feature from 'ol/Feature';
import Overlay from 'ol/Overlay';
import Polygon from 'ol/geom/Polygon';
import LineString from 'ol/geom/LineString';
import Circle from 'ol/style/Circle';
import Fill from 'ol/style/Fill';
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Draw from 'ol/interaction/Draw';
import SnapInteraction from 'ol/interaction/Snap';

import { getArea, getLength } from 'ol/sphere';

var dmgis = dmgis || {};
(function (dmgis) {
    // 定义枚举类型
    dmgis.enum = dmgis.enum || {};

    // 确保枚举类型是新对象，而不是引用已经存在的枚举对象
    Object.assign(dmgis.enum, {
        DMGISTileType: {
            Service: 1, //地图服务发布瓦片
            Publish: 2 //直接发布瓦片文件夹
        },
        GaodeType: {
            VEC: 1, //矢量图（含路网、含注记）
            VEC0: 2, //矢量图（含路网，不含注记）
            IMG: 3, //影像底图（不含路网，含注记）
            IMG0: 4, //影像底图（不含路网、不含注记）
            RIMG: 5, //影像路图（含路网，含注记）
            RIMG0: 6 //影像路网（含路网，不含注记）
        },
        BaiduType: {
            VEC: 1,
            IMG: 2
        },
        TiandituType: {
            VEC: 1, //矢量地图
            CVA: 2, //矢量标签
            IMG: 3, //影像地图
            CIA: 4, //影像标签
            TER: 5, //地形图
            CTA: 6 //地形标签
        }
    });

    // 对象定义
    dmgis.object = dmgis.object || {};

    // Point 类定义
    dmgis.object.Point = function (numX, numY, info) {
        this.x = numX;
        this.y = numY;
        this.info = info;
    };

    // Envelope 类定义
    dmgis.object.Envelope = function () {
        var self = this; // 保存this上下文
        this.minx = 8176078.237521;
        this.miny = 465041.899497;
        this.maxx = 15037685.885628;
        this.maxy = 7326649.547604;

        this.getWidth = function () {
            return self.maxx - self.minx;
        };

        this.getHeight = function () {
            return self.maxy - self.miny;
        };

        // 缩放矩形
        this.scale = function (factor) {
            var center = this.getCenter();
            this.makeFromCenter(center, this.getWidth() * factor, this.getHeight() * factor);
        };

        // 得到中心点
        this.getCenter = function () {
            return new dmgis.object.Point(self.minx + self.getWidth() / 2, self.miny + self.getHeight() / 2);
        };

        // 中心点设置矩形
        this.makeFromCenter = function (center, width, height) {
            self.minx = center.x - width / 2;
            self.maxx = center.x + width / 2;
            self.miny = center.y - height / 2;
            self.maxy = center.y + height / 2;
        };

        // 初始矩形
        this.init = function (env) {
            self.minx = env.minx;
            self.miny = env.miny;
            self.maxx = env.maxx;
            self.maxy = env.maxy;
        };

        this.initextent = function (extent) {
            self.minx = extent[0];
            self.maxx = extent[2];
            self.miny = extent[1];
            self.maxy = extent[3];
        };

        this.initenv = function (minx, miny, maxx, maxy) {
            self.minx = Math.min(minx, maxx);
            self.maxx = Math.max(minx, maxx);
            self.miny = Math.min(miny, maxy);
            self.maxy = Math.max(miny, maxy);
        };
    };

    dmgis.object.SpatialQuery = function () {
        this.strSql = 'dmgis_id>0'; //查询条件
        this.env = null; //查询矩形范围i  矩形和多边形只能用一个
        this.strPos = null; //查询多边形范围  子多边形之间用*号  244 244;345 345;645 543*343 321;334 765;432 321
        this.init = init;
        this.GetXmlString = GetXmlString;

        function GetXmlString() {
            var sAXLText = '<SPATIALQUERY>';
            if (this.strSql != null && this.strSql.length > 1) {
                this.strSql = this.strSql.replace('<', '%%');
                sAXLText = sAXLText + '<QUERY where="' + this.strSql + '"/>';
            }
            if (this.env != null) {
                sAXLText =
                    sAXLText +
                    '<ENVELOPE maxy="' +
                    this.env.maxy +
                    '" maxx="' +
                    this.env.maxx +
                    '" miny="' +
                    this.env.miny +
                    '" minx="' +
                    this.env.minx +
                    '"/>';
            }
            if (this.strPos != null && this.strPos.length > 1) {
                sAXLText = sAXLText + '<POLYGON coords="' + this.strPos + '"/>';
            }
            sAXLText = sAXLText + '</SPATIALQUERY>';
            return sAXLText;
        }

        function init(svr) {
            this.strSql = svr.strSql;
            this.env = null;
            if (svr.env != null) {
                this.env = new dmgis.object.Envelope();
                this.env.init(svr.env);
            }
            this.strPos = svr.strPos;
        }
    };

    dmgis.object.Chartvalue = function (lookupfield, outlineclr, outlinewid, strcolor) {
        this.lookupfield = lookupfield; //字段名
        this.outlineclr = outlineclr; //外框颜色
        this.outlinewid = outlinewid; //外框宽
        this.strcolor = strcolor; //颜色
    };

    dmgis.object.Tm = function () {
        this.type = 1; //专题图的类型 0直方图 1饼图
        this.Barkd = 20; //直方图的宽度
        this.Barhd = 10; //直方图的厚度
        this.Barfx = 0; //直方图的方向
        this.Minsize = 0;
        this.Maxsize = 50; //图屏幕的大小
        this.Minvalue = 0;
        this.Maxvalue = 500; //图显示数据的大小
        this.Transparency = 0; //是否透明 1透明 0不透明
        this.Pie = 0; //饼图是否为半圆
        this.tmFieldSet = []; //专题图字段(为Dmchartvalue数组)
        this.GetXmlString = GetXmlString; //得到xml
        this.AddTmField = AddTmField; //添加专题字段
        function GetXmlString() {
            var sAXLText = '<CHARTSYMBOL type="' + this.type + '" minsize="' + this.Minsize + '"';
            sAXLText = sAXLText + ' minvalue="' + this.Minvalue + '" maxsize="' + this.Maxsize + '"';
            sAXLText = sAXLText + ' maxvalue="' + this.Maxvalue + '" transparency="' + this.Transparency + '"';
            sAXLText =
                sAXLText +
                ' pie="' +
                this.Pie +
                '" barfx="' +
                this.Barfx +
                '" barhd="' +
                this.Barhd +
                '" barkd="' +
                this.Barkd +
                '" >';
            var num = this.tmFieldSet.length;
            for (var i = 0; i < num; i++) {
                sAXLText =
                    sAXLText +
                    '<CHARTVALUE lookupfield ="' +
                    this.tmFieldSet[i].lookupfield +
                    '" outline ="' +
                    this.tmFieldSet[i].outlineclr +
                    '" outlinewid="' +
                    this.tmFieldSet[i].outlinewid +
                    '" color="' +
                    this.tmFieldSet[i].strcolor +
                    '"  />';
            }
            sAXLText = sAXLText + '</CHARTSYMBOL>';
            return sAXLText;
        }

        function AddTmField(lookupfield, outlineclr, outlinewid, strcolor) {
            var len = this.tmFieldSet.length;
            this.tmFieldSet.push(len);
            this.tmFieldSet[len] = new dmgis.object.Chartvalue(lookupfield, outlineclr, outlinewid, strcolor);
            return true;
        }
    };

    dmgis.object.HighDisp = function () {
        this.type = 0; //高亮的类型    (3 为假，0为查询 1索 2号)
        this.isNod = 0; //高亮是否为节点
        this.strHighIndexSet = '569,562'; //高亮索引实体集合字符  1，2，3，4
        this.strHighIDSet = null; //高亮实体号集合字符   1，2，3，4
        this.sqlHigh = new dmgis.object.SpatialQuery(); //高亮的条件  SpatialQuery
        this.GetXmlString = GetXmlString;

        function GetXmlString() {
            var sAXLText = '';
            if (this.type == 0) {
                sAXLText = '<DISPHIGH type="' + this.type + '"  objtype="' + this.isNod + '">';
                sAXLText = sAXLText + this.sqlHigh.GetXmlString();
                sAXLText = sAXLText + '</DISPHIGH>';
            } else if (this.type == 1) {
                sAXLText = '<DISPHIGH type="' + this.type + '"  objtype="' + this.isNod + '">';
                sAXLText = sAXLText + '<INDEXLIST list="' + this.strHighIndexSet + '"/>';
                sAXLText = sAXLText + '</DISPHIGH>';
            } else if (this.type == 2) {
                sAXLText = '<DISPHIGH type="' + this.type + '"  objtype="' + this.isNod + '">';
                sAXLText = sAXLText + '<IDLIST list="' + this.strHighIndexSet + '"/>';
                sAXLText = sAXLText + '</DISPHIGH>';
            }

            return sAXLText;
        }
    };

    dmgis.object.Layer = function () {
        this.name = '未知'; //图层名称
        this.visible = 1; //是否可见
        this.newpath = ''; //新的文件路径  newpath只支持雷达图和影象图，影象图只支持卫星文件的修改
        this.radrangle = 230; //雷达图的公里范围
        this.hdSet = null; //高亮显示地方  HighDisp[]
        this.tmset = null; //专题图条件 Tm[]
        this.GetXmlString = GetXmlString;

        function GetXmlString() {
            var sAXLText =
                '<LAYERDEF name="' +
                this.name +
                '" radrangle="' +
                this.radrangle +
                '"  visible="' +
                '1' +
                '" newpath="' +
                this.newpath +
                '">';

            if (this.hdSet != null) {
                var num = this.hdSet.length;
                for (var i = 0; i < num; i++) {
                    sAXLText = sAXLText + this.hdSet[i].GetXmlString();
                }
            }
            if (this.tmset != null) {
                var numt = this.tmset.length;
                for (var j = 0; j < numt; j++) {
                    sAXLText = sAXLText + this.tmset[j].GetXmlString();
                }
            }
            sAXLText =
                sAXLText +
                '<DISPHIGH type="0" objtype="0"><SPATIALQUERY><ENVELOPE minx="73.44128" miny="18.15983" maxx="135.08693" maxy="53.56177"/></SPATIALQUERY></DISPHIGH></LAYERDEF>';
            //'<ENVELOPE minx="73.44128" miny="18.15983" maxx="135.08693" maxy="53.56177"/>'<QUERY where="dmgis_id>0"/>
            return sAXLText;
        }
    };

    dmgis.object.LayerDisp = function () {
        this.name = '';
        this.visible = 1;
    };

    dmgis.object.FeatureQueryParam = function () {
        this.Attribute = 1; //是否有属性
        this.BeginRecord = 0; //开始记录
        this.Envelop = 1; //是否有矩形
        this.FeatureLimit = 10000; //返回记录最大数
        this.Geometry = 1; //是否有坐标
        this.GlobalEnvelope = 1; //是否有集合的外围矩形
        this.Node = 0; //节点标志
    };

    dmgis.object.RcoVal = function () {
        this.fldname = ''; //字段名
        this.fldval = ''; //字段值
        this.fldtype = ''; //字段类型
    };

    dmgis.object.ServiceInfo = function () {
        this.serverPath = '';
        this.prjRect = null;
        this.layers = null;
    };

    dmgis.object.ImgServiceParam = function () {
        this.serverName = '世界地图'; //服务名称
        this.statesn = '-1'; //服务的密码（如果小于0为
        this.imgHig = 400; //地图宽高
        this.imgWid = 400;
        this.DispRect = new dmgis.object.Envelope(); //地图的范围
        this.layers = null; //dmgis.object.Layer[]
        this.GetXmlString = GetXmlString; //得到XML
        this.ResetService = ResetService; //通过得到的服务还原地图
        this.SetLayerVisible = SetLayerVisible; //设置一个图层显示
        this.AddLayerHDisp = AddLayerHDisp; //为一个图层添加高亮,返回高亮自己设置
        this.AddLayerTm = AddLayerTm; //为一个图层添加专题图
        this.ClearLayerHDisp = ClearLayerHDisp; //清除一个图层的高亮
        this.ClearLayerTm = ClearLayerTm; //清除一个图层的专题图
        this.SetLayerNewPath = SetLayerNewPath; //设置新的文件

        function GetXmlString() {
            var sAXLText;
            sAXLText = '<?xml version="1.0" encoding="UTF-8"?><DMGISXML version="1.1">';
            sAXLText = sAXLText + '<REQUEST>';
            sAXLText = sAXLText + '<GET_IMAGE width="' + this.imgWid + '" height="' + this.imgHig + '" ';
            sAXLText =
                sAXLText +
                'minx="' +
                this.DispRect.minx +
                '" miny="' +
                this.DispRect.miny +
                '" maxx="' +
                this.DispRect.maxx +
                '" maxy="' +
                this.DispRect.maxy +
                '" disp="1"' +
                ' bclr="255,255,255"' +
                '>';
            if (this.layers != null) {
                sAXLText = sAXLText + '<LAYERLIST>';
                var num = this.layers.length;
                for (var i = 0; i < num; i++) {
                    sAXLText = sAXLText + this.layers[i].GetXmlString();
                }
                sAXLText = sAXLText + '</LAYERLIST>';
            }
            sAXLText = sAXLText + '</GET_IMAGE></REQUEST></DMGISXML>';
            return sAXLText;
        }

        //还原设置  svr为DmMapServiceInfo
        function ResetService(svr) {
            if (svr == null || svr.prjRect == undefined) {
                return;
            }
            this.DispRect.minx = svr.prjRect.minx;
            this.DispRect.miny = svr.prjRect.miny;
            this.DispRect.maxx = svr.prjRect.maxx;
            this.DispRect.maxy = svr.prjRect.maxy;
            //初始化图层
            this.layers = null;
            this.layers = [];
            var num = svr.layers.length;

            for (var i = 0; i < num; i++) {
                this.layers.push(i);
                this.layers[i] = new dmgis.object.Layer();
                this.layers[i].name = svr.layers[i].name;
                this.layers[i].visible = svr.layers[i].visible;
            }
            //console.log(this.layers, '12312layers')
        }
        //设置一个图层显示
        function SetLayerVisible(layername, Is) {
            var num = this.layers.length;
            for (var i = 0; i < num; i++) {
                if (this.layers[i].name == layername) {
                    this.layers[i].visible = Is;
                    return true;
                }
            }
            return false;
        }
        //设置新的文件
        function SetLayerNewPath(layername, path, drangle) {
            var num = this.layers.length;
            for (var i = 0; i < num; i++) {
                if (this.layers[i].name == layername) {
                    this.layers[i].newpath = path;
                    if (drangle > 0) this.layers[i].radrangle = drangle;
                    return true;
                }
            }
            return false;
        }
        //为一个图层添加高亮,返回高亮自己设置
        function AddLayerHDisp(layername) {
            var num = this.layers.length;
            for (var i = 0; i < num; i++) {
                if (this.layers[i].name == layername) {
                    if (this.layers[i].hdSet == null) {
                        this.layers[i].hdSet = [];
                    }
                    var len = this.layers[i].hdSet.length;
                    this.layers[i].hdSet.push(len);

                    this.layers[i].hdSet[len] = new dmgis.object.HighDisp();

                    return this.layers[i].hdSet[len];
                }
            }
            return null;
        }
        //为一个图层添加专题图
        function AddLayerTm(layername) {
            var num = this.layers.length;
            for (var i = 0; i < num; i++) {
                if (this.layers[i].name == layername) {
                    if (this.layers[i].tmset == null) {
                        this.layers[i].tmset = []; //该图层专题图数组，存放专题图信息
                    }
                    var len = this.layers[i].tmset.length; //多个字段专题图？
                    this.layers[i].tmset.push(len);
                    this.layers[i].tmset[len] = new dmgis.object.Tm(); //专题图信息
                    return this.layers[i].tmset[len]; //返回专题图信息
                }
            }
            return null;
        }
        //清除一个图层的高亮
        function ClearLayerHDisp(layername) {
            var num = this.layers.length;
            for (var i = 0; i < num; i++) {
                if (this.layers[i].name == layername) {
                    this.layers[i].hdSet = null;
                    return true;
                }
            }
            return false;
        }
        //清除一个图层的专题图
        function ClearLayerTm(layername) {
            var num = this.layers.length;
            for (var i = 0; i < num; i++) {
                if (this.layers[i].name == layername) {
                    this.layers[i].tmset = null;
                    return true;
                }
            }
            return false;
        }
        //根据图层名称获取图层对象
        this.GetLayerByName = function (name) {
            for (var i = 0; i <= this.layers.length - 1; i++) {
                if (this.Layers[i].name == name) {
                    return this.Layers[i];
                }
            }
        };
    };

    dmgis.object.FeatureServiceParam = function () {
        this.serverName = '世界地图'; //服务名称
        this.strlayername = '行政区'; //查询的图层
        this.param = new dmgis.object.FeatureQueryParam(); //查询参数
        this.sql = new dmgis.object.SpatialQuery(); //查询条件
        this.type = 0; //查询类型0查询1索引2实体号
        this.strlist = ''; //索引号或实体号
        this.GetXmlString = GetXmlString; //得到xml
        this.SetIndexSet = SetIndexSet; //设置索引
        this.SetIdSet = SetIdSet; //设置实体

        //设置索引
        function SetIndexSet(str) {
            this.type = 1;
            this.strlist = str;
        }

        //设置实体
        function SetIdSet(str) {
            this.type = 2;
            this.strlist = str;
        }

        function GetXmlString() {
            var sAXLText;
            sAXLText = '<?xml version="1.0" encoding="UTF-8"?><DMGISXML version="1.1">';
            sAXLText = sAXLText + '<REQUEST>';
            sAXLText =
                sAXLText +
                '<GET_FEATURES  attributes="' +
                this.param.Attribute +
                '" beginrecord="' +
                this.param.BeginRecord +
                '" envelope="' +
                this.param.Envelop +
                '" featurelimit="' +
                this.param.FeatureLimit +
                '" geometry="' +
                this.param.Geometry +
                '" globalenvelope="' +
                this.param.GlobalEnvelope +
                '"';
            sAXLText = sAXLText + ' layername="' + this.strlayername + '" nodflag="' + this.param.Node + '">';
            sAXLText = sAXLText + '<GETOBJ type="' + this.type + '">';
            if (this.type == 1) {
                sAXLText = sAXLText + '<INDEXLIST list="' + this.strlist + '"/>';
            } else if (this.type == 2) {
                sAXLText = sAXLText + '<IDLIST list="' + this.strlist + '"/>';
            } else if (this.type == 0) {
                sAXLText = sAXLText + this.sql.GetXmlString();
            }
            sAXLText = sAXLText + '</GETOBJ>';
            sAXLText = sAXLText + '</GET_FEATURES>';
            sAXLText = sAXLText + '</REQUEST>';
            sAXLText = sAXLText + '</DMGISXML>';
            return sAXLText;
        }
    };

    dmgis.object.BufferServiceParam = function () {
        this.serverName = '世界地图'; //服务名称
        this.statesn = '-1'; //服务的密码（如果小于0为无态）
        this.strlayername = '行政区'; //查询的图层
        this.type = 0; //类型 0为索引1为实体号
        this.no = 0; //索引或实体号
        this.blc = 20000.0; //缓冲范围
        this.isNod = 0; //是否节点
        this.GetXmlString = GetXmlString;

        function GetXmlString() {
            var sAXLText;
            sAXLText = '<?xml version="1.0" encoding="UTF-8"?><DMGISXML version="1.1">';
            sAXLText = sAXLText + '<REQUEST>';
            sAXLText = sAXLText + '<GET_BUFFER';
            sAXLText =
                sAXLText +
                ' type="' +
                this.type +
                '" nodflag="' +
                this.isNod +
                '" layername="' +
                this.strlayername +
                '"';
            sAXLText = sAXLText + ' objindex="' + this.no + '"';
            sAXLText = sAXLText + ' bufferblc="' + this.blc + '"/>';
            sAXLText = sAXLText + '</REQUEST>';
            sAXLText = sAXLText + '</DMGISXML>';
            return sAXLText;
        }
    };

    dmgis.object.PathServiceParam = function () {
        this.serverName = '世界地图'; //服务名称
        this.statesn = '-1'; //服务的密码（如果小于0为无态）
        this.strlayername = '行政区'; //查询的图层
        this.type = 0; //类型 0点１号２索３公交
        this.ipos = '12658733.54958 3287847.75389'; //开始节点  公交ipos和epos为站点名 点为点坐标(33 44)
        this.epos = '12683917.90057 3273792.40307'; //结束节点
        this.ex = 1565.9810040136717; //路径分析误差
        this.GetXmlString = GetXmlString; //得到xml
        function GetXmlString() {
            var sAXLText;
            sAXLText = '<?xml version="1.0" encoding="UTF-8"?><DMGISXML version="1.1">';
            sAXLText = sAXLText + '<REQUEST>';
            sAXLText = sAXLText + '<GET_PATH';
            sAXLText = sAXLText + ' type="' + this.type + '" layername="' + this.strlayername + '"';
            sAXLText = sAXLText + ' ipos="' + this.ipos + '"';
            sAXLText = sAXLText + ' epos="' + this.epos + '"';
            sAXLText = sAXLText + ' wx="' + this.ex + '"/>';
            sAXLText = sAXLText + '</REQUEST>';
            sAXLText = sAXLText + '</DMGISXML>';
            return sAXLText;
        }
    };

    dmgis.object.DmRcoVal = function (fldname, fldval) {
        this.fldname = fldname;
        this.fldval = fldval;
    };

    dmgis.object.BuildServiceParam = function () {
        this.serverName = '世界地图'; //服务名称
        this.statesn = '-1'; //服务的密码（如果小于0为无态）
        this.strlayername = '主要城市'; //查询的图层
        this.type = 0; //0 为 添加实体  1为删除实体  2为修改实体图形坐标  3为修改修改属性 4为保存图层
        this.index = 0;
        this.strPos = '';
        this.rco = null; //DmRcoVal的集合
        this.GetXmlString = GetXmlString;

        function GetXmlString() {
            var sAXLText;
            sAXLText = '<?xml version="1.0" encoding="UTF-8"?><DMGISXML version="1.1">';
            sAXLText = sAXLText + '<REQUEST>';
            sAXLText = sAXLText + '<Build ';
            sAXLText =
                sAXLText +
                'type ="' +
                this.type +
                '" index="' +
                this.index +
                '" cor="' +
                this.strPos +
                '" layername="' +
                this.strlayername +
                '">';
            if (this.rco != null) {
                var num = this.rco.length;
                for (var i = 0; i < num; i++) {
                    sAXLText =
                        sAXLText + '<Field name="' + this.rco[i].fldname + '" val="' + this.rco[i].fldval + '" />';
                }
            }
            sAXLText = sAXLText + '</Build>';
            sAXLText = sAXLText + '</REQUEST>';
            sAXLText = sAXLText + '</DMGISXML>';
            return sAXLText;
        }
    };

    dmgis.object.ImageInfo = function () {
        this.imgUrl = ''; //此属性图片的网络位置
        this.imgPath = ''; //此属性图片的本地位置
        this.extent = new dmgis.object.Envelope(); //实际的地理范围
    };

    dmgis.object.WorkObj = function () {
        this.id = 0; //实体号
        this.index = 0; //索引号
        this.type = 8; //坐标类型 (0点1线面2复合体)
        this.strPnt = null; //点坐标
        this.strCor = null; //坐标 (线区和复合体线坐标）
        this.strRng = null; //坐标（复合替面坐标）
        this.env = null; //范围
        this.rec = null; //属性信息DmRcoVal集合
    };

    dmgis.object.FeatureInfo = function () {
        this.objset = null; //实体集合
        this.genv = null; //范围
        this.znum = null; //这次查询总的实体数
        this.isMore = null; //是否还有数据
    };

    dmgis.object.BufferInfo = function () {
        this.strPos = null; //缓冲的坐标
        this.env = new dmgis.object.Envelope(); //范围
    };

    dmgis.object.PathInfo = function () {
        this.strPos = ''; //坐标
        this.strSta = ''; //站点
        this.strLin = ''; //线路
        this.ll = 0; //长度
        this.env = new dmgis.object.Envelope(); //范围
    };

    dmgis.object.LengthPoint = function (_x, _y, _distance, _info) {
        this.x = _x;
        this.y = _y;
        this.Distance = _distance;
        this.info = _info || null;
    };

    dmgis.object.GridRequestPar = function (_url, _data, _DataTemplate, _TagTemplate, _success) {
        this.url = _url;
        this.data = _data;
        this.DataTemplate = _DataTemplate;
        this.TagTemplate = _TagTemplate;
        this.success = _success;
    };

    //工具类
    dmgis.tool = dmgis.tool ? dmgis.tool : {};
    dmgis.tool = function () {};

    dmgis.tool.Min = function (val1, val2) {
        if (val1 > val2) return val2;
        else return val1;
    };

    dmgis.tool.Max = function (val1, val2) {
        if (val1 < val2) return val2;
        else return val1;
    };

    dmgis.tool.Intersect = function (srect1, srect2) {
        var dt1 = new dmgis.object.Point(srect1.xmin, srect1.ymin);
        if (dmgis.tool.DotInRect(dt1, srect2)) return true;
        var dt2 = new dmgis.object.Point(srect1.xmin, srect1.ymax);
        if (dmgis.tool.DotInRect(dt2, srect2)) return true;
        var dt3 = new dmgis.object.Point(srect1.xmax, srect1.ymax);
        if (dmgis.tool.DotInRect(dt3, srect2)) return true;
        var dt4 = new dmgis.object.Point(srect1.xmax, srect1.ymin);
        if (dmgis.tool.DotInRect(dt4, srect2)) return true;
        return false;
    };

    dmgis.tool.DotInRect = function (pnt, rect) {
        if (pnt.x < rect.xmin) return false;
        if (pnt.x > rect.xmax) return false;
        if (pnt.y < rect.ymin) return false;
        if (pnt.y > rect.ymax) return false;
        return true;
    };

    dmgis.tool.AndRect = function (srect1, srect2) {
        var ds = new dmgis.object.Envelope();
        ds.minx = srect1.minx > srect2.minx ? srect1.minx : srect2.minx;
        ds.miny = srect1.miny > srect2.miny ? srect1.miny : srect2.miny;
        ds.maxx = srect1.maxx < srect2.maxx ? srect1.maxx : srect2.maxx;
        ds.maxy = srect1.maxy < srect2.maxy ? srect1.maxy : srect2.maxy;
        return ds;
    };

    dmgis.tool.DotInPolygon = function (PQarray, XDot, YDot) {
        var CheckFlg = false;
        var cout = 0;
        if (PQarray[PQarray.length - 1].x == XDot && PQarray[PQarray.length - 1].y == YDot) {
            CheckFlg = true;
        } else {
            if (
                (PQarray[PQarray.length - 1].y > YDot && PQarray[0].y < YDot) ||
                (PQarray[PQarray.length - 1].y < YDot && PQarray[0].y > YDot)
            ) {
                var tmpX = parseInt(
                    (PQarray[0].x * YDot +
                        PQarray[PQarray.length - 1].x * PQarray[0].y -
                        PQarray[PQarray.length - 1].x * YDot -
                        PQarray[0].x * PQarray[PQarray.length - 1].y) /
                        (PQarray[0].y - PQarray[PQarray.length - 1].y)
                );
                if (tmpX == XDot) CheckFlg = true;
                else if (tmpX > XDot) cout++;
            }
        }
        if (!CheckFlg) {
            for (var i = 0; i < PQarray.length - 1; i++) {
                if (PQarray[i].x == XDot && PQarray[i].y == YDot) {
                    CheckFlg = true;
                    break;
                } else {
                    if (
                        (PQarray[i].y > YDot && PQarray[i + 1].y < YDot) ||
                        (PQarray[i].y < YDot && PQarray[i + 1].y > YDot)
                    ) {
                        tmpX = parseInt(
                            (PQarray[i].x * YDot +
                                PQarray[i + 1].x * PQarray[i].y -
                                PQarray[i + 1].x * YDot -
                                PQarray[i].x * PQarray[i + 1].y) /
                                (PQarray[i].y - PQarray[i + 1].y)
                        );
                        if (tmpX == XDot) {
                            CheckFlg = true;
                            break;
                        } else if (tmpX > XDot) cout++;
                    }
                }
            }
        }
        if (!CheckFlg && cout % 2 == 1) CheckFlg = true;
        return CheckFlg;
    };

    dmgis.tool.GetRectCenter = function (startPoint, endPoint) {
        return new dmgis.object.Point((endPoint.x + startPoint.x) / 2, (endPoint.y + startPoint.y) / 2);
    };

    dmgis.tool.Rad = function (d) {
        return (d * Math.PI) / 180.0;
    };

    // dmgis.tool.GetDistance = (function(Point1, Point2) {
    //     var radLat1 = rad(Point1.y);
    //     var radLat2 = rad(Point2.y);
    //     var a = radLat1 - radLat2;
    //     var b = rad(Point1.x) - rad(Point2.x);
    //     var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    //     s = s * EARTH_RADIUS;
    //     s = Math.round(s * 10000) / 10000;
    //     return s;
    // })

    // dmgis.tool.GetLengthBy2Pnt = (function(startPoint, endPoint) {
    //     if (startPoint.x < 180 && startPoint.x > 0) {
    //         return GetDistance(startPoint, endPoint);
    //     }
    //     return Math.sqrt((endPoint.x - startPoint.x) * (endPoint.x - startPoint.x) + (endPoint.y - startPoint.y) * (endPoint.y - startPoint.y));
    // })

    dmgis.tool.GetLengthUnit = function (CoorLength) {
        if (CoorLength < 1000) {
            return CoorLength.toFixed(1) + '</font>米';
        } else {
            return (CoorLength / 1000).toFixed(1) + '</font>公里';
        }
    };

    dmgis.tool.GetAreaUnit = function (CoorLength) {
        if (CoorLength < 1000000) {
            return CoorLength.toFixed(1) + '</font>平方米';
        } else if (CoorLength >= 1000000 && CoorLength < 10000000000) {
            return (CoorLength / 1000000).toFixed(1) + '</font>平方公里';
        } else {
            return (CoorLength / 10000000000).toFixed(1) + '</font>万平方公里';
        }
    };

    dmgis.tool.CalculateArea = function (PointArray) {
        var area = 0;
        var i, j;
        var xjyi, xiyj;
        var xydiff;
        j = PointArray.length - 1;
        for (i = 0; i <= PointArray.length - 1; i++) {
            xiyj = PointArray[i].x * PointArray[j].y;
            xjyi = PointArray[j].x * PointArray[i].y;
            xydiff = xiyj - xjyi;
            area += xydiff;
            j = i;
        }
        area = Math.abs(area / 2);
        if (PointArray[0].x < 180 && PointArray[0].x > 0) {
            area = area * 111000 * 111000;
        }
        return area;
    };

    dmgis.tool.Rot = function (x, y, angle) {
        var a = (angle * -3.1415926) / 180;
        var ix = x * Math.cos(a) - y * Math.sin(a);
        var iy = x * Math.sin(a) + y * Math.cos(a);
        return [parseInt(ix), parseInt(iy)];
    };

    dmgis.tool.GetRectMinMax = function (pointArray) {
        var rect = new dmgis.object.Envelope();
        rect.minx = pointArray[0].x;
        rect.maxx = pointArray[0].x;
        rect.miny = pointArray[0].y;
        rect.maxy = pointArray[0].y;
        for (var i = 0; i <= pointArray.length - 1; i++) {
            if (pointArray[i].x < rect.minx) {
                rect.minx = pointArray[i].x;
            }

            if (pointArray[i].x > rect.maxx) {
                rect.maxx = pointArray[i].x;
            }

            if (pointArray[i].y < rect.miny) {
                rect.miny = pointArray[i].y;
            }

            if (pointArray[i].y > rect.maxy) {
                rect.maxy = pointArray[i].y;
            }
        }
        return rect;
    };

    dmgis.tool.Curve = function (xq, m) {
        //xq为坐标二维数组,m为已知点个数.
        var resultArray = [];
        var i,
            j,
            k = 20;
        var lx1, ly1; //曲线点坐标
        var t0, t1, t2, t3;
        lx1 = (xq[0].x + 4.0 * xq[1].x + xq[2].x) / xq.length;
        ly1 = (xq[0].y + 4.0 * xq[1].y + xq[2].y) / xq.length;
        for (i = 1; i < m - 2; i++) {
            for (j = 0; j <= k; j++) {
                t3 = (1.0 * j) / k;
                t0 = 1 - t3;
                t0 = (t0 * t0 * t0) / 6.0;
                t1 = ((3.0 * t3 - 6.0) * t3 * t3 + 4.0) / 6.0;
                t2 = (((3 - 3 * t3) * t3 + 3) * t3 + 1) / 6.0;
                t3 = 1.0 - t0 - t1 - t2;
                lx1 = xq[i - 1].x * t0 + xq[i].x * t1 + xq[i + 1].x * t2 + xq[i + 2].x * t3;
                ly1 = xq[i - 1].y * t0 + xq[i].y * t1 + xq[i + 1].y * t2 + xq[i + 2].y * t3;
                resultArray.push(new dmgis.object.Envelope(lx1, ly1));
            }
        }
        return resultArray;
    };

    dmgis.tool.CurvePnt = function (p) {
        //p为已知点,已知点有N+3个
        //var q = [];
        var r = [];
        p.push(p[0]);
        p.push(p[1]);
        p.push(p[2]);
        var a = 0,
            b = 0,
            c = 0,
            d = 0,
            k = 0,
            s1 = 0,
            s2 = 0;
        var x = [];
        var y = [];
        var i; //,color
        for (i = 0; i < p.length - 3; i++) {
            x[i] = p[i].x;
            y[i] = p[i].y;
            a = a + x[i];
            b = b + y[i];
        }
        a = a / (p.length - 3); //a,b 为重心 N为顶点个数
        b = b / (p.length - 3);
        c = (x[0] + 4 * x[1] + x[2]) / 6; //c,d为点X[1]Y[1]所对应的缩小点
        d = (y[0] + 4 * y[1] + y[2]) / 6;
        s1 = (x[1] - a) * (x[1] - a) + (y[1] - b) * (y[1] - b);
        s1 = Math.sqrt(s1);
        s2 = (c - a) * (c - a) + (d - b) * (d - b);
        s2 = Math.sqrt(s2);
        k = s1 / s2;
        x[p.length - 3 + 2] = (p[p.length - 3 + 2][0] + p[3].x) / 2;
        y[p.length - 3 + 2] = (p[p.length - 3 + 2][1] + p[3].y) / 2;
        for (i = 0; i < p.length - 3 + 2; i++) {
            x[i] = (p[i].x + p[i + 1].x) / 2; //x[i]y[i]为p的中点构成的多边形
            y[i] = (p[i].y + p[i + 1].y) / 2;
        }

        for (i = 0; i < p.length - 3 + 3; i++) {
            r[i] = new dmgis.object.Envelope();
            r[i].x = k * (p[i].x - a) + a;
            r[i].y = k * (p[i].y - b) + b;
        }
        return r;
    };

    dmgis.tool.ArrayToString = function (PointArray) {
        var resultStr = '';
        for (var i = 0; i <= PointArray.length - 1; i++) {
            resultStr += PointArray[i].x + ' ' + PointArray[i].y + ';';
        }
        resultStr = resultStr + PointArray[0].x + ' ' + PointArray[0].y;
        return resultStr;
    };

    dmgis.tool.StringToArray = function (strPoint) {
        var result = [];
        var row = strPoint.split(';');
        for (var i = 0; i <= row.length - 1; i++) {
            result.push(new dmgis.object.Point(parseFloat(row[i].split(' ')[0]), parseFloat(row[i].split(' ')[1])));
        }
        return result;
    };

    dmgis.tool.StringToArray2 = function (strPoint, flag) {
        var result = [];
        var row = strPoint.split(flag);
        for (var i = 0; i <= row.length - 1; i++) {
            result.push(new dmgis.object.Point(parseFloat(row[i].split(' ')[0]), parseFloat(row[i].split(' ')[1])));
        }
        return result;
    };

    dmgis.tool.transWin32ColorToHtml = function (color) {
        var htmlColor = '#ffffff';
        color = parseInt(color);
        try {
            var r = (color & 255).toString(16);
            var g = ((color >> 8) & 255).toString(16);
            var b = ((color >> 16) & 255).toString(16);
            htmlColor =
                '#' + (r.length < 2 ? '0' + r : r) + (g.length < 2 ? '0' + g : g) + (b.length < 2 ? '0' + b : b);
        } catch (e) {
            alert(e.message);
        }
        return htmlColor;
    };

    //递归获取元素的的坐标X
    // dmgis.tool.getElementOffsetX = (function(obj) {
    //     if ($(obj).parent().length != 0) {
    //         return obj.offsetLeft + dmgis.tool.getElementOffsetX($(obj).parent()[0]);
    //     } else {
    //         if (obj.offsetLeft == undefined) {
    //             return 0;
    //         }
    //         return obj.offsetLeft;
    //     }
    // })

    //递归获取元素的的坐标Y
    // dmgis.tool.getElementOffsetY = (function(obj) {
    //     if ($(obj).parent().length != 0) {
    //         return obj.offsetTop + dmgis.tool.getElementOffsetY($(obj).parent()[0]);
    //     } else {
    //         if (obj.offsetTop == undefined) {
    //             return 0;
    //         }
    //         return obj.offsetTop;
    //     }
    // })

    //获取竖向滚动条滚动数
    dmgis.tool.getBodyScrollTop = function () {
        if ('pageYOffset' in window) {
            return window.scrollY;
        } else if (document.compatMode === 'BackCompat') {
            return document.body.scrollTop;
        } else {
            return document.documentElement.scrollTop;
        }
    };

    //获取横向滚动条滚动数
    dmgis.tool.getBodyScrollLeft = function () {
        if ('pageXOffset' in window) {
            return window.scrollX;
        } else if (document.compatMode === 'BackCompat') {
            return document.body.scrollLeft;
        } else {
            return document.documentElement.scrollLeft;
        }
    };

    dmgis.tool.DptoSpOL = function (map, x, y) {
        var ObjCoor = [];
        ObjCoor[0] = x;
        ObjCoor[1] = y;
        var ScreenCoor = map.getPixelFromCoordinate(ObjCoor);
        var SpCoor = new dmgis.object.Point(ScreenCoor[0], ScreenCoor[1]);
        return SpCoor;
    };

    //服务类
    dmgis.service = dmgis.service ? dmgis.service : {};
    dmgis.service = function () {};

    dmgis.service.GetServices = function (response) {
        try {
            var parser = new DOMParser();
            var axlResponse = parser.parseFromString(response, 'text/xml');
            //var axlResponse = response; //LoadXml(response);
            //var list = null;
            if (axlResponse.getElementsByTagName('Services').length >= 1) {
                //list = axlResponse.getElementsByTagName("Services");
                var layerList = null;
                if (axlResponse.getElementsByTagName('Service').length >= 1) {
                    layerList = axlResponse.getElementsByTagName('Service');
                    var strservice = [];
                    for (var i = 0; i < layerList.length; i++) {
                        strservice.push(i);
                        strservice[i] = layerList[i].attributes.getNamedItem('name').nodeValue;
                    }
                    return strservice;
                }
            }
            return null;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetProjServers = function (response) {
        try {
            var list = null;
            var serverInfo = null;

            var parser = new DOMParser();
            var axlResponse = parser.parseFromString(response, 'text/xml');

            if (axlResponse.getElementsByTagName('SERVER').length >= 1) {
                list = axlResponse.getElementsByTagName('SERVER');
                serverInfo = new dmgis.object.ServiceInfo();
                serverInfo.serverPath = list[0].attributes.getNamedItem('prjname').nodeValue;
                serverInfo.prjRect = new dmgis.object.Envelope();
                serverInfo.prjRect.miny = parseFloat(list[0].attributes.getNamedItem('miny').nodeValue);
                serverInfo.prjRect.minx = parseFloat(list[0].attributes.getNamedItem('minx').nodeValue);
                serverInfo.prjRect.maxx = parseFloat(list[0].attributes.getNamedItem('maxx').nodeValue);
                serverInfo.prjRect.maxy = parseFloat(list[0].attributes.getNamedItem('maxy').nodeValue);
                var layerList = null;
                if (axlResponse.getElementsByTagName('LAYER').length >= 1) {
                    layerList = axlResponse.getElementsByTagName('LAYER');
                    serverInfo.layers = [];
                    for (var i = 0; i < layerList.length; i++) {
                        serverInfo.layers.push(i);
                        serverInfo.layers[i] = new dmgis.object.LayerDisp();
                        serverInfo.layers[i].name = layerList[i].attributes.getNamedItem('name').nodeValue;
                        serverInfo.layers[i].visible = parseInt(
                            layerList[i].attributes.getNamedItem('visible').nodeValue
                        );
                    }
                }
            }
            return serverInfo;
        } catch (e) {
            alert(e);
            return null;
        }
    };

    dmgis.service.GetImageInfo = function (response) {
        try {
            var parser = new DOMParser();
            var axlResponse = parser.parseFromString(response, 'text/xml');
            //var axlResponse = response;
            var inf = new dmgis.object.ImageInfo();
            if (axlResponse.getElementsByTagName('ENVELOPE').length == 1) {
                var noderefput = axlResponse.getElementsByTagName('ENVELOPE');
                inf.extent.minx = parseFloat(noderefput[0].attributes.getNamedItem('minx').nodeValue);
                inf.extent.miny = parseFloat(noderefput[0].attributes.getNamedItem('miny').nodeValue);
                inf.extent.maxx = parseFloat(noderefput[0].attributes.getNamedItem('maxx').nodeValue);
                inf.extent.maxy = parseFloat(noderefput[0].attributes.getNamedItem('maxy').nodeValue);
            }
            if (axlResponse.getElementsByTagName('OUTPUT').length == 1) {
                noderefput = axlResponse.getElementsByTagName('OUTPUT');
                inf.imgUrl = noderefput[0].attributes.getNamedItem('url').nodeValue;
                inf.imgPath = noderefput[0].attributes.getNamedItem('file').nodeValue;
                return inf;
            }
            return null;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetFeatureInfo = function (response) {
        try {
            var parser = new DOMParser();
            var axlResponse = parser.parseFromString(response, 'text/xml');
            //var axlResponse = response;
            if (axlResponse.getElementsByTagName('FEATURES').length == 1) {
                //得到实体
                var noderefput = axlResponse.getElementsByTagName('FEATURES');
                if (noderefput.length > 0) {
                    var feature = new dmgis.object.FeatureInfo();
                    //得到实体的节点
                    var node = noderefput[0];
                    //得到实体的子节点
                    var nodelist = node.childNodes;
                    var num = nodelist.length;
                    if (num > 0) {
                        //得到外围矩形

                        if (nodelist[num - 1].nodeName == 'ENVELOPE') {
                            num = num - 1;
                            feature.genv = new dmgis.object.Envelope();
                            feature.genv.minx = parseFloat(nodelist[num].attributes.getNamedItem('minx').nodeValue);
                            feature.genv.miny = parseFloat(nodelist[num].attributes.getNamedItem('miny').nodeValue);
                            feature.genv.maxx = parseFloat(nodelist[num].attributes.getNamedItem('maxx').nodeValue);
                            feature.genv.maxy = parseFloat(nodelist[num].attributes.getNamedItem('maxy').nodeValue);
                        }

                        //得到总数
                        feature.znum = parseInt(nodelist[num - 1].attributes.getNamedItem('count').nodeValue);
                        feature.isMore = parseInt(nodelist[num - 1].attributes.getNamedItem('hasmore').nodeValue);

                        num = num - 1;
                        if (num > 0) {
                            feature.objset = [];
                            for (var i = 0; i < num; i++) {
                                feature.objset.push(i);
                                feature.objset[i] = new dmgis.object.WorkObj();
                                var node1 = nodelist[i];
                                feature.objset[i].id = parseInt(node1.attributes.getNamedItem('id').nodeValue);
                                feature.objset[i].index = parseInt(node1.attributes.getNamedItem('index').nodeValue);
                                var nodelist1 = node1.childNodes;
                                for (var j = 0; j < nodelist1.length; j++) {
                                    //外围矩形
                                    if (nodelist1[j].nodeName == 'ENVELOPE') {
                                        feature.objset[i].env = new dmgis.object.Envelope();
                                        feature.objset[i].env.minx = parseFloat(
                                            nodelist1[j].attributes.getNamedItem('minx').nodeValue
                                        );
                                        feature.objset[i].env.miny = parseFloat(
                                            nodelist1[j].attributes.getNamedItem('miny').nodeValue
                                        );
                                        feature.objset[i].env.maxx = parseFloat(
                                            nodelist1[j].attributes.getNamedItem('maxx').nodeValue
                                        );
                                        feature.objset[i].env.maxy = parseFloat(
                                            nodelist1[j].attributes.getNamedItem('maxy').nodeValue
                                        );
                                    }
                                    //属性
                                    if (nodelist1[j].nodeName == 'FIELDS') {
                                        var node2 = nodelist1[j];
                                        var fnum = node2.attributes.length;
                                        feature.objset[i].rec = [];
                                        for (var z = 0; z < fnum; z++) {
                                            feature.objset[i].rec.push(z);
                                            feature.objset[i].rec[z] = new dmgis.object.RcoVal();
                                            feature.objset[i].rec[z].fldname = node2.attributes.item(z).nodeName;
                                            feature.objset[i].rec[z].fldval = node2.attributes.item(z).nodeValue;
                                        }
                                    }
                                    //坐标
                                    if (nodelist1[j].nodeName == 'POS') {
                                        var node3 = nodelist1[j];
                                        var type = parseInt(node3.attributes.getNamedItem('type').nodeValue);
                                        feature.objset[i].type = type;
                                        if (type == 0) {
                                            feature.objset[i].strPnt = node3.attributes.getNamedItem('pnt').nodeValue;
                                        } else if (type == 1) {
                                            feature.objset[i].strCor = node3.attributes.getNamedItem('cod').nodeValue;
                                        } else if (type == 2) {
                                            feature.objset[i].strPnt = node3.attributes.getNamedItem('pnt').nodeValue;
                                            feature.objset[i].strCor = node3.attributes.getNamedItem('cod').nodeValue;
                                            feature.objset[i].strRng = node3.attributes.getNamedItem('rng').nodeValue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return feature;
                }
            }
            return null;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetBufferInfo = function (response) {
        try {
            var parser = new DOMParser();
            var axlResponse = parser.parseFromString(response, 'text/xml');
            //var axlResponse = response;
            var buffer = null;
            if (axlResponse.getElementsByTagName('ENVELOPE').length == 1) {
                buffer = new dmgis.object.BufferInfo();
                var noderefput = axlResponse.getElementsByTagName('ENVELOPE');
                buffer.env.minx = parseFloat(noderefput[0].attributes.getNamedItem('minx').nodeValue);
                buffer.env.miny = parseFloat(noderefput[0].attributes.getNamedItem('miny').nodeValue);
                buffer.env.maxx = parseFloat(noderefput[0].attributes.getNamedItem('maxx').nodeValue);
                buffer.env.maxy = parseFloat(noderefput[0].attributes.getNamedItem('maxy').nodeValue);
            }
            if (axlResponse.getElementsByTagName('POLYGON').length == 1) {
                noderefput = axlResponse.getElementsByTagName('POLYGON');
                buffer.strPos = noderefput[0].attributes.getNamedItem('coords').nodeValue;
            }
            return buffer;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetPathInfo = function (response) {
        try {
            var parser = new DOMParser();
            var axlResponse = parser.parseFromString(response, 'text/xml');
            //var axlResponse = response;
            var path = null;
            if (axlResponse.getElementsByTagName('ENVELOPE').length == 1) {
                path = new dmgis.object.PathInfo();
                var noderefput = axlResponse.getElementsByTagName('ENVELOPE');
                path.env.minx = parseFloat(noderefput[0].attributes.getNamedItem('minx').nodeValue);
                path.env.miny = parseFloat(noderefput[0].attributes.getNamedItem('miny').nodeValue);
                path.env.maxx = parseFloat(noderefput[0].attributes.getNamedItem('maxx').nodeValue);
                path.env.maxy = parseFloat(noderefput[0].attributes.getNamedItem('maxy').nodeValue);
            }
            if (axlResponse.getElementsByTagName('PATH').length == 1) {
                noderefput = axlResponse.getElementsByTagName('PATH');
                path.strPos = noderefput[0].attributes.getNamedItem('coords').nodeValue;
                path.ll = parseInt(noderefput[0].attributes.getNamedItem('dis').nodeValue);
                path.strLin = noderefput[0].attributes.getNamedItem('nodlist').nodeValue;
                path.strSta = noderefput[0].attributes.getNamedItem('arclist').nodeValue;
            }
            return path;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetBuildInfo = function (response) {
        try {
            var parser = new DOMParser();
            var axlResponse = parser.parseFromString(response, 'text/xml');
            //var axlResponse = response;
            var builfinfo = null;
            if (axlResponse.getElementsByTagName('OBJ').length == 1) {
                builfinfo = new dmgis.object.WorkObj();
                //得到实体
                var noderefput = axlResponse.getElementsByTagName('OBJ');
                if (noderefput.length > 0) {
                    //得到实体的节点
                    var node = noderefput[0];
                    if (parseInt(node.attributes.getNamedItem('SC').nodeValue) == 1) {
                        builfinfo.index = parseInt(node.attributes.getNamedItem('index').nodeValue);
                    }
                }
                return builfinfo;
            }
            return null;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetWMSFeatureInfo = function (response) {
        try {
            var parser = new DOMParser();
            var axlResponse = parser.parseFromString(response, 'text/xml');
            //var axlResponse = response;
            if (axlResponse.getElementsByTagName('Layers').length == 1) {
                //Layers
                //得到图层
                var noderefput = axlResponse.getElementsByTagName('Layer');
                if (noderefput.length > 0) {
                    for (var k = 0; k < noderefput.length; k++) {
                        var nodelayer = noderefput[k];
                        var layerName = nodelayer.attributes.getNamedItem('name').nodeValue;
                        console.log(layerName);

                        var featurenodes = nodelayer.getElementsByTagName('Feature');

                        var feature = new dmgis.object.FeatureInfo();
                        if (featurenodes.length > 0) {
                            feature.objset = [];
                            for (var kk = 0; kk < featurenodes.length; kk++) {
                                feature.objset.push(kk);
                                feature.objset[kk] = new dmgis.object.WorkObj();
                                var featurenode = featurenodes[kk];
                                var fnum = featurenode.attributes.length;
                                feature.objset[kk].rec = [];
                                for (var z = 0; z < fnum; z++) {
                                    feature.objset[kk].rec.push(z);
                                    feature.objset[kk].rec[z] = new dmgis.object.RcoVal();
                                    feature.objset[kk].rec[z].fldname = featurenode.attributes.item(z).nodeName;
                                    feature.objset[kk].rec[z].fldval = featurenode.attributes.item(z).nodeValue;
                                }
                            }
                        }
                        return feature;
                    }
                }
            }
            return null;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetWFSDescribeFeatureInfo = function (response) {
        try {
            var parser = new DOMParser();
            var axlResponse = parser.parseFromString(response, 'text/xml');
            //var axlResponse = response;
            if (axlResponse.getElementsByTagName('xsd:schema').length == 1) {
                //xsd:schema
                var feature = new dmgis.object.FeatureInfo();

                var sequences = axlResponse.getElementsByTagName('xsd:sequence');

                var count = sequences.length;
                if (count == 1) {
                    count = 0;
                    feature.objset = [];
                    feature.objset.push(count);
                    feature.objset[count] = new dmgis.object.WorkObj();
                    feature.objset[count].rec = [];
                    //得到图层
                    var elements = sequences[0].getElementsByTagName('xsd:element');
                    if (elements.length > 0) {
                        feature.objset[count].rec = [];
                        for (var k = 0; k < elements.length; k++) {
                            var featurenode = elements[k];
                            feature.objset[count].rec.push(k);
                            feature.objset[count].rec[k] = new dmgis.object.RcoVal();
                            feature.objset[count].rec[k].fldname =
                                featurenode.attributes.getNamedItem('name').nodeValue;
                            feature.objset[count].rec[k].fldtype =
                                featurenode.attributes.getNamedItem('type').nodeValue;
                        }
                        return feature;
                    }
                }
            }
            return null;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetWFSFeatureInfo = function (response, serlayname) {
        try {
            var parser = new DOMParser();
            var axlResponse = parser.parseFromString(response, 'text/xml');
            //var axlResponse = response;
            if (axlResponse.getElementsByTagName('wfs:FeatureCollection').length == 1) {
                //xsd:schema
                var feature = new dmgis.object.FeatureInfo();

                var sequences = axlResponse.getElementsByTagName(serlayname);

                var num = sequences.length;
                feature.objset = [];
                for (var i = 0; i < num; i++) {
                    feature.objset.push(i);
                    feature.objset[i] = new dmgis.object.WorkObj();
                    feature.objset[i].rec = [];
                    var elements = sequences[i].children;
                    if (elements.length > 0) {
                        feature.objset[i].rec = [];
                        for (var k = 0; k < elements.length; k++) {
                            var featurenode = elements[k];
                            feature.objset[i].rec.push(k);
                            feature.objset[i].rec[k] = new dmgis.object.RcoVal();
                            feature.objset[i].rec[k].fldname = featurenode.tagName.split(':')[1];
                            feature.objset[i].rec[k].fldval = featurenode.innerHTML;
                        }
                    }
                }
                return feature;
            }
            return null;
        } catch (e) {
            return null;
        }
    };

    // 对象定义          子类
    dmgis.olmap = dmgis.olmap || {};
    //GaodeLayer
    dmgis.olmap.GaodeLayer = dmgis.olmap.GaodeLayer ? dmgis.olmap.GaodeLayer : {};
    dmgis.olmap.GaodeLayer = function (layerName, options) {
        //var options = options ? options : {};
        var attributions;
        if (options.attributions !== undefined) {
            attributions = options.attributions;
        } else {
            attributions = [
                '&copy; <a class="ol-attribution-amap" ' + 'href="http://ditu.amap.com/">' + '高德地图</a>'
            ];
        }

        var url;
        if (options.mapType == dmgis.enum.GaodeType.VEC) {
            url = 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7';
        } else if (options.mapType == dmgis.enum.GaodeType.VEC0) {
            url = 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=7';
        } else if (options.mapType == dmgis.enum.GaodeType.IMG) {
            url = 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=6';
        } else if (options.mapType == dmgis.enum.GaodeType.IMG0) {
            url = 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=6';
        } else if (options.mapType == dmgis.enum.GaodeType.RIMG) {
            url = 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8';
        } else if (options.mapType == dmgis.enum.GaodeType.RIMG0) {
            url = 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=8';
        }
        var source = new XYZ({
            attributions: attributions,
            crossOrigin: 'anonymous', //跨域
            cacheSize: options.cacheSize,
            projection: getProjection('EPSG:3857'),
            url: url,
            wrapX: options.wrapX !== undefined ? options.wrapX : true
        });
        // var option = {
        //     title: layerName,
        //     source: source
        // };

        var gaodelayer = new TileLayer({
            name: layerName,
            source: source
        });
        return gaodelayer;
    };
    //ol.inherits(dmgis.olmap.GaodeLayer, TileLayer);

    //BaiduLayer
    dmgis.olmap.BaiduLayer = dmgis.olmap.BaiduLayer ? dmgis.olmap.BaiduLayer : {};
    dmgis.olmap.BaiduLayer = function (layerName, options) {
        //var options = options ? options : {};
        var attributions;
        if (options.attributions !== undefined) {
            attributions = options.attributions;
        } else {
            attributions = [
                '&copy; <a class="ol-attribution-baidumap" ' + 'href="http://map.baidu.com/">' + '百度地图</a>'
            ];
        }

        var extent = [72.004, 0.8293, 137.8347, 55.8271];

        var baiduMercator = new Projection({
            code: 'baidu',
            extent: applyTransform(extent, projzh.ll2bmerc),
            units: 'm'
        });

        addProjection(baiduMercator);
        addCoordinateTransforms('EPSG:4326', baiduMercator, projzh.ll2bmerc, projzh.bmerc2ll);
        addCoordinateTransforms('EPSG:3857', baiduMercator, projzh.smerc2bmerc, projzh.bmerc2smerc);
        var resolutions = [];
        //重新定义分辨率
        for (var i = 0; i < 19; i++) {
            resolutions[i] = Math.pow(2, 18 - i);
        }
        var tilegrid = new TileGrid({
            origin: [0, 0],
            resolutions: resolutions,
            extent: applyTransform(extent, projzh.ll2bmerc),
            tileSize: [256, 256]
        });
        var satUrls = [0, 1, 2, 3, 4].map(function (sub) {
            return 'http://shangetu' + sub + '.map.bdimg.com/it/u=x={x};y={y};z={z};v=009;type=sate&fm=46&udt=20150601';
        });
        var urls = [0, 1, 2, 3, 4].map(function (sub) {
            return (
                'http://online' +
                sub +
                '.map.bdimg.com/onlinelabel/qt=tile&x={x}&y={y}&z={z}&v=009&styles=pl&udt=20170301&scaler=1&p=1'
            );
        });
        var source = new TileImage({
            attributions: attributions,
            crossOrigin: 'anonymous', //跨域
            cacheSize: options.cacheSize,
            // projection: ol.proj.get('EPSG:3857'),
            projection: 'baidu',
            tileGrid: tilegrid,
            tileUrlFunction: function (tileCoord) {
                //重写索引检索方法
                if (!tileCoord) return '';
                console.log(tileCoord, 'tileCoord2321312');
                var z = tileCoord[0];
                var x = tileCoord[1];
                var y = Math.abs(tileCoord[2]) - 1;
                var hash = (x << z) + y;
                var index = hash % urls.length;
                index = index < 0 ? index + urls.length : index;
                if (options.mapType == dmgis.enum.BaiduType.IMG) {
                    return satUrls[index].replace('{x}', x).replace('{y}', y).replace('{z}', z);
                }
                return urls[index].replace('{x}', x).replace('{y}', y).replace('{z}', z);
            },
            wrapX: options.wrapX !== undefined ? options.wrapX : true
        });
        var baiduLayer = new TileLayer({
            name: layerName,
            source: source
        });
        return baiduLayer;
        // var options = {
        //     title: layerName,
        //     source: source
        // };
        // ol.layer.Tile.call(this, options);
    };

    //TiandituLayer
    dmgis.olmap.TiandituLayer = dmgis.olmap.TiandituLayer ? dmgis.olmap.TiandituLayer : {};
    dmgis.olmap.TiandituLayer = function (layerName, options) {
        //var options = options ? options : {};
        var attributions;
        if (options.attributions !== undefined) {
            attributions = options.attributions;
        } else {
            attributions = [
                '&copy; <a class="ol-attribution-tianmap" ' + 'href="http://www.tianditu.cn/">' + '天地图</a>'
            ];
        }

        var url;
        if (options.mapType == dmgis.enum.TiandituType.IMG) {
            url = 'http://t{0-4}.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=3b41248c204d6f92ca4fbd7da0386da6'; //基础影像
            //title = "基础影像";
        } else if (options.mapType == dmgis.enum.TiandituType.CIA) {
            url = 'http://t{0-4}.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=3b41248c204d6f92ca4fbd7da0386da6'; //带标签影像
            //title = "基础影像标签";
        } else if (options.mapType == dmgis.enum.TiandituType.VEC) {
            url = 'http://t{0-4}.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=3b41248c204d6f92ca4fbd7da0386da6'; //基础地图
            //title = "基础地图";
        } else if (options.mapType == dmgis.enum.TiandituType.CVA) {
            url = 'http://t{0-4}.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=3b41248c204d6f92ca4fbd7da0386da6'; //基础地图
            //title = "基础地图标签";
        } else if (options.mapType == dmgis.enum.TiandituType.TER) {
            url = 'http://t{0-4}.tianditu.com/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=3b41248c204d6f92ca4fbd7da0386da6'; //地形图
            //title = "地形图";
        } else if (options.mapType == dmgis.enum.TiandituType.CTA) {
            url = 'http://t{0-4}.tianditu.com/DataServer?T=cta_w&x={x}&y={y}&l={z}&tk=3b41248c204d6f92ca4fbd7da0386da6'; //地形图
            //title = "地形图标注";
        }

        var source = new XYZ({
            attributions: attributions,
            projection: getProjection('EPSG:3857'),
            cacheSize: options.cacheSize,
            // crossOrigin: "anonymous",
            opaque: options.opaque !== undefined ? options.opaque : true,
            maxZoom: options.maxZoom !== undefined ? options.maxZoom : 19,
            reprojectionErrorThreshold: options.reprojectionErrorThreshold, //异常处理
            url: url,
            wrapX: options.wrapX
        });
        var tiandituLayer = new TileLayer({
            name: layerName,
            source: source
        });
        return tiandituLayer;
    };

    //OSMLayer
    dmgis.olmap.OSMLayer = dmgis.olmap.OSMLayer ? dmgis.olmap.OSMLayer : {};
    dmgis.olmap.OSMLayer = function (layerName) {
        var source = new OSM();
        var OSMLayer = new TileLayer({
            name: layerName,
            source: source
        });
        return OSMLayer;
    };

    //ArcgisLayer
    dmgis.olmap.ArcgisLayer = dmgis.olmap.ArcgisLayer ? dmgis.olmap.ArcgisLayer : {};
    dmgis.olmap.ArcgisLayer = function (layerName, tileUrl, options) {
        //var options = options ? options : {};
        var projection = options.projection ? getProjection(options.projection) : getProjection('EPSG:3857');
        // 坐标原点
        var origin = options.origin;
        // 分辨率
        var resolutions = options.resolutions;
        //地图范围
        var fullExtent = options.extent;
        //瓦片大小
        var tileSize = options.tileSize ? options.tileSize : 256;
        var maxZoom = options.maxZoom ? options.maxZoom : 18;
        var minZoom = options.minZoom ? options.minZoom : 0;
        var tileGrid = new TileGrid({
            tileSize: tileSize,
            origin: origin,
            extent: fullExtent,
            resolutions: resolutions
        });
        // 瓦片数据源
        var source = new XYZ({
            tileGrid: tileGrid,
            projection: projection,
            url: tileUrl,
            minZoom: minZoom,
            maxZoom: maxZoom
        });
        var arcgisLayer = new TileLayer({
            name: layerName,
            source: source
        });
        return arcgisLayer;
    };

    //----------------DM瓦片----------------//
    dmgis.olmap.TileLayer = dmgis.olmap.TileLayer ? dmgis.olmap.TileLayer : {};
    dmgis.olmap.TileLayer = function (layerName, mapService, tileType, options) {
        //var layerName = layerName;
        //var mapService = mapService;
        //var tileType = tileType;
        //var options = options ? options : {};
        var resolutions = [];
        var minx = options.extent[0];
        //var miny = options.extent[1];
        var maxx = options.extent[2];
        var maxy = options.extent[3];
        var projection = options.projection ? getProjection(options.projection) : getProjection('EPSG:3857');
        var tileSize = options.tileSize ? options.tileSize : 256;
        var maxZoom = options.maxZoom ? options.maxZoom : 18;
        var minZoom = options.minZoom ? options.minZoom : 1;
        // 计算百度使用的分辨率
        for (var i = 0; i <= maxZoom; i++) {
            resolutions[i] = (maxx - minx) / Math.pow(2, i) / tileSize;
        }

        var tilegrid = new TileGrid({
            origin: [minx, maxy], // 设置原点坐标
            resolutions: resolutions, // 设置分辨率
            tileSize: tileSize,
            minZoom: minZoom,
            maxZoom: maxZoom,
            extent: options.extent
        });
        var source = new XYZ({
            crossOrigin: 'anonymous', //解决跨域问题，避免截图产生空白问题
            extent: options.extent,
            tileGrid: tilegrid,
            maxZoom: maxZoom,
            minZoom: minZoom,
            projection: projection,
            tileUrlFunction: function (tileCoord) {
                console.log(tileCoord, 'tileCoord2321312');
                var z = tileCoord[0];
                var y = Math.pow(2, z) - 2 - (Math.abs(tileCoord[2]) - 1);
                var x = tileCoord[1];
                if (tileType == dmgis.enum.DMGISTileType.Service) {
                    var imgUrl = mapService + '/dts/GetDmgisTileImage/' + layerName + '/{x}/{y}/{z}';
                    return imgUrl.replace('{z}', z).replace('{x}', x).replace('{y}', y);
                } else {
                    imgUrl = mapService + '/' + layerName + '/{z}/{y}/{x}.jpg';
                    return imgUrl.replace('{z}', z).replace('{x}', x).replace('{y}', y);
                }
            }
        });
        var dmTileLayer = new TileLayer({
            name: layerName,
            source: source,
            wrapX: true,
            zIndex: 4
        });
        return dmTileLayer;
    };

    //----------------DM服务ServiceLayer----------------//
    dmgis.olmap.ServiceLayer = dmgis.olmap.ServiceLayer || {};
    //dmgis.olmap.ServiceLayer = dmgis.olmap.ServiceLayer ? dmgis.olmap.ServiceLayer : {};
    dmgis.olmap.ServiceLayer = function (layerName, mapService, options) {
        //var options = options ? options : {};
        this.imgsvrParam = null;
        this.service = null;
        this.mapService = mapService;
        this.serverName = layerName;
        this.maxZoom = options.maxZoom ? options.maxZoom : 18;
        this.minZoom = options.minZoom ? options.minZoom : 0;
        this.opacity = options.opacity ? options.opacity : 1;
        this.projection = options.projection ? getProjection(options.projection) : getProjection('EPSG:4326');
        this.ImgMapService = new dmgis.object.ImgServiceParam();
        this.InitService = InitService;
        this.serviceLayer = null;

        async function InitService() {
            var url = this.mapService + '/dms/GetService/' + this.serverName;
            var obj = this;
            let data = null;
            try {
                // 使用 Axios 发送 get 请求
                const response = await axios.get(url);
                if (response.data == '服务请求异常!') {
                    alert('服务请求异常!');
                    return;
                }
                data = response.data;
                var svr = new dmgis.service.GetProjServers(response.data);
                obj.service = svr;
                obj.ImgMapService.ResetService(svr);
                obj.ImgMapService.serverName = obj.serverName;
            } catch (error) {
                alert('请求失败: ' + error.message + error.status);
            }
            return parseXMLToObjectArray(data);
        }
        // this.serviceLayer = new ImageLayer({
        //     name: layerName
        // });
        // return serviceLayer;
    };
    //ol.inherits(dmgis.olmap.ServiceLayer, ol.layer.Image);
    dmgis.olmap.ServiceLayer.prototype.RefreshMap1 = function (serviceLayer, imgSvrParam, zoom) {
        var iLevel = zoom;
        if (iLevel >= this.minZoom && iLevel <= this.maxZoom) {
            this.ImgMapService = imgSvrParam;
            if (this.ImgMapService.layers != null) {
                var extent = this.ImgMapService.DispRect;
                //var mapextent = map.getView().calculateExtent(map.getSize());
                var url =
                    this.mapService +
                    '/dms/GetImage/' +
                    this.serverName +
                    '?param=' +
                    encodeURIComponent(this.ImgMapService.GetXmlString());
                var imagesource = new ImageStatic({
                    url: url,
                    projection: this.projection,
                    crossOrigin: 'Anonymous',
                    // imageExtent: mapextent
                    imageExtent: [extent.minx, extent.miny, extent.maxx, extent.maxy]
                });
                //this.serviceLayer.setSource(imagesource);
                serviceLayer.setSource(imagesource);
            }
        }
    };
    dmgis.olmap.ServiceLayer.prototype.RefreshMap = function (serviceLayer, imgSvrParam, param, zoom) {
        var iLevel = zoom;
        if (iLevel >= this.minZoom && iLevel <= this.maxZoom) {
            this.ImgMapService = imgSvrParam;
            if (this.ImgMapService.layers != null) {
                var extent = this.ImgMapService.DispRect;
                //var mapextent = map.getView().calculateExtent(map.getSize());
                var url =
                    this.mapService +
                    '/dms/GetImage/' +
                    this.serverName +
                    '?param=<?xml version="1.0" encoding="UTF-8"?>' +
                    objectToXML(param);
                var imagesource = new ImageStatic({
                    url: url,
                    projection: this.projection,
                    crossOrigin: 'Anonymous',
                    // imageExtent: mapextent
                    imageExtent: [extent.minx, extent.miny, extent.maxx, extent.maxy]
                });
                //this.serviceLayer.setSource(imagesource);
                serviceLayer.setSource(imagesource);
            }
        }
    };
    dmgis.olmap.ServiceLayer.prototype.GetImgSvrParam = function () {
        return this.ImgMapService; //new dmgis.object.ImgServiceParam();
    };
    dmgis.olmap.ServiceLayer.prototype.getLayers = function () {
        return this.service.layers;
    };
    //属性服务
    dmgis.olmap.ServiceLayer.prototype.GetFeatureMapService = function (ActiveLayerName = '') {
        var dmFeatureMapService = new dmgis.object.FeatureServiceParam();
        dmFeatureMapService.serverName = this.ImgMapService.serverName; //服务名称
        dmFeatureMapService.strlayername = ActiveLayerName;
        //console.log(dmFeatureMapService)
        return dmFeatureMapService;
    };
    dmgis.olmap.ServiceLayer.prototype.SendFeatureMapService = async function (svr) {
        var self = this;
        this.serviceurl = this.mapService;
        let data;
        var url =
            this.serviceurl + '/dms/GetFeature/' + svr.serverName + '?param=' + encodeURIComponent(svr.GetXmlString());
        try {
            // 使用 Axios 发送 get 请求
            const response = await axios.post(url);
            if (response.data == '服务请求异常!') {
                alert('服务请求异常!');
                return;
            }
            data = response.data;
            var dmGetFeature = new dmgis.service.GetFeatureInfo(response.data);
            //console.log(dmGetFeature);
            self.HandleFeatureInfo(dmGetFeature);
        } catch (error) {
            // alert('请求失败: ' + error.message + error.status);
        }
        return parseXMLToObjectArray(data);
    };
    //缓冲区
    dmgis.olmap.ServiceLayer.prototype.GetBufferMapService = function (ActiveLayerName) {
        var dmBufferMapService = new dmgis.object.BufferServiceParam();
        dmBufferMapService.serverName = this.ImgMapService.serverName; //服务名称
        dmBufferMapService.strlayername = ActiveLayerName; //查询的图层
        dmBufferMapService.type = 0; //0为索引   1为实体号
        dmBufferMapService.no = 3;
        console.log(dmBufferMapService, 'dmBufferMapService1232131312');
        return dmBufferMapService;
    };
    dmgis.olmap.ServiceLayer.prototype.SendBufferMapService = async function (svr) {
        var self = this;
        this.serviceurl = this.mapService;
        var url =
            this.serviceurl +
            '/dms/GetSpatialAnalyse/' +
            svr.serverName +
            '?param=' +
            encodeURIComponent(svr.GetXmlString());
        try {
            // 使用 Axios 发送 get 请求
            const response = await axios.get(url);
            if (response.data == '服务请求异常!') {
                alert('服务请求异常!');
                return;
            }
            var dmGetBuffer = new dmgis.service.GetBufferInfo(response.data);
            console.log(dmGetBuffer, 'getbuffer213213');
            self.HandleBufferInfo(dmGetBuffer);
        } catch (error) {
            alert('请求失败: ' + error.message + error.status);
        }
    };
    //路径分析
    dmgis.olmap.ServiceLayer.prototype.GetPathMapService = function (ActiveLayerName) {
        var dmPathMapService = new dmgis.object.PathServiceParam();
        dmPathMapService.serverName = this.ImgMapService.serverName; //服务名称
        dmPathMapService.strlayername = ActiveLayerName; //查询的图层
        return dmPathMapService;
    };
    dmgis.olmap.ServiceLayer.prototype.SendPathMapService = async function (svr) {
        var self = this;
        this.serviceurl = this.mapService;
        var url =
            this.serviceurl +
            '/dms/GetPathAnalyse/' +
            svr.serverName +
            '?param=' +
            encodeURIComponent(svr.GetXmlString());
        try {
            // 使用 Axios 发送 get 请求
            const response = await axios.get(url);
            if (response.data == '服务请求异常!') {
                alert('服务请求异常!');
                return;
            }
            var dmGetPath = new dmgis.service.GetPathInfo(response.data);
            self.HandlePathInfo(dmGetPath);
        } catch (error) {
            alert('请求失败: ' + error.message + error.status);
        }
    };
    //属性编辑
    dmgis.olmap.ServiceLayer.prototype.GetBuildMapService = function (ActiveLayerName) {
        var dmBuildMapService = new dmgis.object.BuildServiceParam();
        dmBuildMapService.serverName = this.ImgMapService.serverName; //服务名称
        dmBuildMapService.strlayername = ActiveLayerName; //查询的图层
        console.log(dmBuildMapService);
        return dmBuildMapService;
    };
    //保存工程
    dmgis.olmap.ServiceLayer.prototype.savePrj = async function (svr, layername) {
        this.serviceurl = this.mapService;
        var url =
            this.serviceurl +
            '/dms/GetBuildMap/' +
            svr.serverName +
            '?param=<?xml version="1.0" encoding="UTF-8"?>' +
            objectToXML({
                name: 'DMGISXML',
                version: '1.1',
                children: {
                    name: 'REQUEST',
                    children: {
                        name: 'Build',
                        attributes: {
                            type: '4',
                            layername: layername
                        }
                    }
                }
            });

        let data;
        try {
            // 使用 Axios 发送 请求
            const response = await axios.post(url);
            if (response.data == '服务请求异常!') {
                alert('服务请求异常!');
                return;
            }
            data = response.data;
        } catch (error) {
            alert('请求失败: ' + error.message + error.status);
        }
        return parseXMLToObjectArray(data);
    };
    //属性编辑服务发送
    dmgis.olmap.ServiceLayer.prototype.SendBuildMapService = async function (svr) {
        var self = this;
        this.serviceurl = this.mapService;
        var url =
            this.serviceurl + '/dms/GetBuildMap/' + svr.serverName + '?param=' + encodeURIComponent(svr.GetXmlString());

        let data;
        try {
            // 使用 Axios 发送 请求
            const response = await axios.post(url);
            if (response.data == '服务请求异常!') {
                alert('服务请求异常!');
                return;
            }
            data = response.data;
            // var dmGetBuild = new dmgis.service.GetBuildInfo(response.data);
            // self.HandleBuildInfo(dmGetBuild);
        } catch (error) {
            alert('请求失败: ' + error.message + error.status);
        }
        return parseXMLToObjectArray(data);
    };

    //----------------等值图ContourLayer----------------//
    dmgis.olmap.ContourLayer = dmgis.olmap.ContourLayer ? dmgis.olmap.ContourLayer : {};
    dmgis.olmap.ContourLayer = function (layerName, mapService, options) {
        this.serverName = layerName;
        this.mapService = mapService;
        this.ContoursData = null;
        this.maxZoom = options.maxZoom || 18;
        this.minZoom = options.minZoom || 0;
        this.opacity = options.opacity ? options.opacity : 1;
        this.projection = options.projection ? getProjection(options.projection) : getProjection('EPSG:3857');
        this.contourLayer = null;
    };

    dmgis.olmap.ContourLayer.prototype.UpdateContoursAtt = async function (dataurl) {
        //var self = this;
        var url =
            this.mapService +
            '/pws/CallPlugin/service' +
            '?methodName=contour&postdata=GetInterpolationWork|' +
            encodeURIComponent(dataurl);
        //var postdata = "methodName=contour&postdata=GetInterpolationWork|" + encodeURIComponent(dataurl);
        try {
            // 使用 Axios 发送 请求
            await axios.post(url).then((response) => {
                if (response.data == '服务请求异常!') {
                    alert('服务请求异常!');
                    return;
                }
                this.ContoursData = response.data;
                console.log(this, 'this123');
            });
            //return response.data;
        } catch (error) {
            alert('请求失败: ' + error.message + error.status);
        }
        console.log(this.ContoursData, 'datadzt213123123');
    };
    dmgis.olmap.ContourLayer.prototype.RefreshMap = async function (layer, zoom, mapsize, env) {
        console.log(this);
        var self = this;
        var iLevel = zoom;
        var extent = transformExtent(env, 'EPSG:3857', 'EPSG:4326');
        console.log(this.minZoom, this.maxZoom, zoom, this.ContoursData);
        if (iLevel >= this.minZoom && iLevel <= this.maxZoom) {
            if (self.ContoursData == null) return;
            //var postdata = self.ContoursData + "|" + this.serverName + "|" + mapsize[1] + "|" + mapsize[0] + "|" + extent[0] + "," + (extent[1] - 33200) + "," + extent[2] + "," + (extent[3] - 33200) + "|1";
            var postdata =
                self.ContoursData +
                '|' +
                this.serverName +
                '|' +
                mapsize[1] +
                '|' +
                mapsize[0] +
                '|' +
                extent[0] +
                ',' +
                extent[1] +
                ',' +
                extent[2] +
                ',' +
                extent[3] +
                '|1';
            var obj = this;
            var url =
                this.mapService +
                '/pws/CallPlugin/service' +
                '?methodName=contour&postdata=GetContourPic|' +
                encodeURIComponent(postdata);
            try {
                // 使用 Axios 发送 请求
                const response = await axios.post(url);
                if (response.data == '服务请求异常!') {
                    alert('服务请求异常!');
                    return;
                }
                if (response.data != null && response.data != '') {
                    var imgurl = obj.mapService + '/res/pws/' + response.data;
                    var imagesource = new ImageStatic({
                        url: imgurl,
                        projection: this.projection,
                        crossOrigin: 'Anonymous',
                        imageExtent: env
                    });
                    layer.setSource(imagesource);
                }
            } catch (error) {
                alert('请求失败: ' + error.message + error.status);
            }
        }
    };

    //----------------数据点图层PointDataLayer----------------//
    dmgis.olmap.PointDataLayer = dmgis.olmap.PointDataLayer ? dmgis.olmap.PointDataLayer : {};
    dmgis.olmap.PointDataLayer = function (layerName, mapDivId, map, zIndex, minLevel, maxLevel) {
        this.map = map;
        this.PointsArr = []; //用于保存点类信息的数组
        this.DataTemplate = null;
        this.TagTemplate = null;
        this.IsRemoveOverlay = true; //是否移除叠加图层
        this.MinLevel = minLevel;
        this.MaxLevel = maxLevel;
        this.MouseEvent = 'mouseover'; //标记所使用事件
        this.OverlayWidth = 100; //标记间隔
        this.Visible = true; //是否可见
        this.XmlHttp = null;
        this.coverflag = true;
        this.screenCoor = [];
    };
    //清空数据
    dmgis.olmap.PointDataLayer.prototype.clear = function () {
        this.PointsArr = [];
        if (this.XmlHttp != null) {
            this.XmlHttp.abort();
            this.XmlHttp = null;
        }
    };
    dmgis.olmap.PointDataLayer.prototype.DptoSp = function (x, y) {
        return dmgis.tool.DptoSpOL(this.map, x, y);
    };
    //设置index
    dmgis.olmap.PointDataLayer.prototype.setzIndex = function (index) {
        this.el.css('zIndex', index);
    };
    dmgis.olmap.PointDataLayer.prototype.AddLegend = function (data, lendTitle) {
        this.mapDiv.find('#legend').remove(); //移除图例
        if (data != undefined && data.length > 0) {
            var append = '<table id="legend">';
            append += '<tr><td colspan=2 style="font-weight: bold;">' + lendTitle + '</td></tr>';
            for (var i = data.length - 1; i >= 0; i--) {
                var color = dmgis.tool.transWin32ColorToHtml(data[i].elementColor); //利用Cesium自带的color类工具进行颜色转换，并设置透明度，将rgba颜色转换从css颜色
                append +=
                    '<tr><td style="width:60px;height:32px;background-color:' +
                    color +
                    '"></td><td>' +
                    data[i].elementValue +
                    '</td></tr>';
            }
            append += '</table>';
            this.mapDiv.append(append);
        }
    };
    dmgis.olmap.PointDataLayer.prototype.AddPoint = function (url, data, success) {
        this.PointsArr = [];
        this.removeTag();
        var DataObj = this;
        if (this.XmlHttp != null) {
            //终止请求
            this.XmlHttp.abort();
            this.XmlHttp = null;
        }
        this.XmlHttp = function () {};
        // 使用 Axios 发送 POST 请求
        axios
            .post(url, data)
            .then((response) => {
                // 请求成功，处理响应数据
                let resultData = response.data;
                if (resultData.result && Array.isArray(resultData.result)) {
                    // 如果第一个数据是数组
                    DataObj.PointsArr =
                        resultData.result[0] instanceof Array ? resultData.result[0] : resultData.result;
                } else {
                    DataObj.PointsArr = resultData.result;
                }
                // 添加图例 图例标题 （根据实际情况添加）
                // DataObj.AddLegend(resultData[1], resultData[2]);

                DataObj.screenCoor = DataObj.Draw();

                // 请求成功执行参数 success方法
                if (success !== undefined) {
                    success(DataObj.screenCoor);
                }
            })
            .catch((error) => {
                alert('请求失败: ' + error.message + error.status);
            })
            .finally(() => {
                // 无论请求成功或失败都会执行
                this.XmlHttp = null;
            });
    };

    dmgis.olmap.PointDataLayer.prototype.AddSinglePoint = function (data, DataTemplate, TagTemplate, success) {
        this.PointsArr = [];
        this.removeTag();
        this.DataTemplate = DataTemplate;
        this.TagTemplate = TagTemplate;
        var DataObj = this;
        if (this.XmlHttp != null) {
            //终止jQuery的ajax请求
            this.XmlHttp.abort();
            this.XmlHttp = null;
        }
        DataObj.CacheData = data;
        DataObj.PointsArr = eval(data);
        DataObj.Draw();
        DataObj.XmlHttp = null;
        success(DataObj.PointsArr);
    };
    dmgis.olmap.PointDataLayer.prototype.IsInScreen = function (extent, x, y) {
        if (x < extent[0]) return false;
        if (x > extent[2]) return false;
        if (y < extent[1]) return false;
        if (y > extent[3]) return false;
        return true;
    };
    //绘制点方法
    dmgis.olmap.PointDataLayer.prototype.Draw = function () {
        //this.el.html("");
        if (this.Visible) {
            var iLevel = this.map.getView().getZoom();
            var extent = this.map.getView().calculateExtent(this.map.getSize());
            if (iLevel >= this.MinLevel && iLevel <= this.MaxLevel) {
                var TempArr = [];
                if (this.PointsArr == null) {
                    return;
                }
                for (var i = 0; i < this.PointsArr.length; i++) {
                    //如果是经纬度坐标，需要处理成墨卡托
                    if (this.PointsArr[i].lon < 180 && this.PointsArr[i].lon > -180) {
                        var newcood = transform(
                            [this.PointsArr[i].lon, this.PointsArr[i].lat],
                            'EPSG:4326',
                            'EPSG:3857'
                        );
                        this.PointsArr[i].lon = newcood[0];
                        this.PointsArr[i].lat = newcood[1];
                    }
                    //遍历点集合
                    if (this.IsInScreen(extent, this.PointsArr[i].lon, this.PointsArr[i].lat)) {
                        var ScreenCoor = dmgis.tool.DptoSpOL(this.map, this.PointsArr[i].lon, this.PointsArr[i].lat);
                        if (ScreenCoor == undefined) continue;
                        var num = TempArr.length;
                        var bXjFlag = false;

                        if (this.IsRemoveOverlay) {
                            for (var j = 0; j <= num - 1; j++) {
                                if (
                                    Math.abs(ScreenCoor.x - TempArr[j].x) < this.OverlayWidth &&
                                    Math.abs(ScreenCoor.y - TempArr[j].y) < this.OverlayWidth
                                ) {
                                    bXjFlag = true;
                                    break;
                                }
                            }
                            if (bXjFlag) {
                                continue;
                            }
                        }
                        ScreenCoor.info = this.PointsArr[i];
                        TempArr.push(ScreenCoor);
                    }
                }
            }
        }
        //console.log(TempArr, 'TempArr21312312');
        return TempArr;
    };
    //移除标记
    dmgis.olmap.PointDataLayer.prototype.removeTag = function () {
        //$(".tag", this.mapDiv).html("");
    };
    dmgis.olmap.PointDataLayer.prototype.GetInWinCoor = function (x, y) {
        return new dmgis.object.Point(
            x + dmgis.tool.getBodyScrollLeft() - dmgis.tool.getElementOffsetX(this.mapDiv[0]),
            y + dmgis.tool.getBodyScrollTop() - dmgis.tool.getElementOffsetY(this.mapDiv[0])
        );
    };

    //----------------网格点图层GridPointDataLayer----------------//
    dmgis.olmap.GridPointDataLayer = dmgis.olmap.GridPointDataLayer ? dmgis.olmap.GridPointDataLayer : {};
    dmgis.olmap.GridPointDataLayer = function (layerName, mapDivId, map, zIndex, minLevel, maxLevel) {
        this.map = map;
        this.PointsArr = []; //用于保存点类信息的数组
        this.DataTemplate = null;
        this.TagTemplate = null;
        this.IsRemoveOverlay = true; //是否移除叠加图层
        this.MinLevel = minLevel;
        this.MaxLevel = maxLevel;
        this.MouseEvent = 'mouseover'; //标记所使用事件
        this.OverlayWidth = 100; //标记间隔
        this.Visible = true; //是否可见
        this.XmlHttp = null;
        this.GridCode = ''; //网格点
        this.GridRequestPar = null;
        this.BaseLV = 5; //默认级别
        this.Extent = null;
        this.Resolution = 0;
        this.tileSize = 256;
        this.IndexList = [];
    };
    //清空数据
    dmgis.olmap.GridPointDataLayer.prototype.clear = function () {
        this.PointsArr = [];
        this.GridCode = '';
        this.GridRequestPar = null;
        if (this.XmlHttp != null) {
            this.XmlHttp.abort();
            this.XmlHttp = null;
        }
    };
    //设置index
    dmgis.olmap.GridPointDataLayer.prototype.setzIndex = function (index) {
        this.el.css('zIndex', index);
    };
    //移除标记
    dmgis.olmap.GridPointDataLayer.prototype.removeTag = function () {
        //$(".tag", this.mapDiv).html("");
    };
    dmgis.olmap.GridPointDataLayer.prototype.GetInWinCoor = function (x, y) {
        return new dmgis.object.Point(
            x + dmgis.tool.getBodyScrollLeft() - dmgis.tool.getElementOffsetX(this.mapDiv[0]),
            y + dmgis.tool.getBodyScrollTop() - dmgis.tool.getElementOffsetY(this.mapDiv[0])
        );
    };
    dmgis.olmap.GridPointDataLayer.prototype.DptoSp = function (x, y) {
        return dmgis.tool.DptoSpOL(this.map, x, y);
    };
    dmgis.olmap.GridPointDataLayer.prototype.IsInScreen = function (extent, x, y) {
        if (x < extent[0]) return false;
        if (x > extent[2]) return false;
        if (y < extent[1]) return false;
        if (y > extent[3]) return false;
        return true;
    };

    //获取在范围内网格的索引
    dmgis.olmap.GridPointDataLayer.prototype.GetGridCode = function () {
        var extent = this.map.getView().calculateExtent(this.map.getSize());
        var rectmap = new dmgis.object.Envelope();
        rectmap.initextent(extent); //得到当前大小窗口地图的范围
        if (!dmgis.tool.Intersect(rectmap, this.Extent)) return;
        var imgRowCount = Math.pow(2, this.BaseLV);
        var dx = (this.Extent.maxx - this.Extent.minx) / imgRowCount;
        var andrect = dmgis.tool.AndRect(rectmap, this.Extent);
        var startCol = Math.floor((andrect.minx - this.Extent.minx) / dx); //开始列
        var endCol = Math.floor((andrect.maxx - this.Extent.minx) / dx) + 1; //结束列
        var startRow = Math.floor((andrect.miny - this.Extent.miny) / dx); //开始行
        var endRow = Math.floor((andrect.maxy - this.Extent.miny) / dx) + 1; //结束行
        for (var i = startRow; i <= endRow; i++) {
            for (var j = startCol; j <= endCol; j++) {
                var code = i * this.tileSize + j;
                if (this.GridCode.indexOf('' + code) == -1) {
                    this.GridCode += code + ',';
                }
            }
        }
        //console.log(this.GridCode)
    };
    //根据格网索引请求点  blv为编码网格，一般都为5;
    dmgis.olmap.GridPointDataLayer.prototype.AddPoint = function (
        blv,
        extent,
        url,
        data,
        DataTemplate,
        TagTemplate,
        success
    ) {
        this.BaseLV = blv;
        this.Extent = extent;
        this.Resolution = (extent.maxx - extent.minx) / Math.pow(2, blv) / this.tileSize;
        this.GridRequestPar = new dmgis.object.GridRequestPar(url, data, DataTemplate, TagTemplate, success); //GridRequestPar：Grid请求参数
        this.removeTag();
        //var obj = this.map;
        this.DataTemplate = DataTemplate;
        this.TagTemplate = TagTemplate;
        //var DataObj = this;

        if (this.XmlHttp != null) {
            this.XmlHttp.abort();
            this.XmlHttp = null;
        }
        this.GridCode = '';
        var res = this.map.getView().getResolution(); //当前分辨率
        if (res <= this.Resolution) {
            this.GetGridCode();
        }
        if (this.GridCode != '') {
            this.GridCode = this.GridCode.substring(0, this.GridCode.length - 1);
            var DataObj = this;
            this.XmlHttp = function () {};
            // 使用 Axios 发送 POST 请求
            axios
                .post(url, { param: this.GridCode })
                .then((response) => {
                    // 请求成功，处理响应数据
                    let resultData = response.data;
                    if (resultData.result == undefined) return;
                    DataObj.PointsArr = eval(resultData.result);

                    DataObj.screenCoor = DataObj.Draw();

                    if (success !== undefined) {
                        success(DataObj.screenCoor);
                    }
                })
                .catch((error) => {
                    alert('请求失败: ' + error.message + error.status);
                })
                .finally(() => {
                    // 无论请求成功或失败都会执行
                    this.XmlHttp = null;
                });
            return true;
        } else {
            return false;
        }
    };
    dmgis.olmap.GridPointDataLayer.prototype.RefreshMap = function () {
        this.el.html('');
        if (this.Visible) {
            var iLevel = this.map.getView().getZoom();

            if (iLevel >= this.MinLevel && iLevel <= this.MaxLevel) {
                var res = this.map.getView().getResolution(); //当前分辨率
                if (res > this.Resolution) return;
                this.AddPoint(
                    this.BaseLV,
                    this.Extent,
                    this.GridRequestPar.url,
                    this.GridRequestPar.data,
                    this.GridRequestPar.DataTemplate,
                    this.GridRequestPar.TagTemplate,
                    this.GridRequestPar.success
                );
            }
        }
    };
    dmgis.olmap.GridPointDataLayer.prototype.Draw = function () {
        var TempArr = [];
        if (this.PointsArr == null) {
            return;
        }
        var extent = this.map.getView().calculateExtent(this.map.getSize());
        for (var i = 0; i < this.PointsArr.length; i++) {
            //如果是经纬度坐标，需要处理成墨卡托
            if (this.PointsArr[i].lon < 180 && this.PointsArr[i].lon > -180) {
                var newcood = transform([this.PointsArr[i].lon, this.PointsArr[i].lat], 'EPSG:4326', 'EPSG:3857');
                this.PointsArr[i].lon = newcood[0];
                this.PointsArr[i].lat = newcood[1];
            }
            //遍历点集合
            if (this.IsInScreen(extent, this.PointsArr[i].lon, this.PointsArr[i].lat)) {
                var ScreenCoor = dmgis.tool.DptoSpOL(this.map, this.PointsArr[i].lon, this.PointsArr[i].lat);
                if (ScreenCoor == undefined) continue;
                var num = TempArr.length;
                var bXjFlag = false;

                if (this.IsRemoveOverlay) {
                    for (var j = 0; j <= num - 1; j++) {
                        if (
                            Math.abs(ScreenCoor.x - TempArr[j].x) < this.OverlayWidth &&
                            Math.abs(ScreenCoor.y - TempArr[j].y) < this.OverlayWidth
                        ) {
                            bXjFlag = true;
                            break;
                        }
                    }
                    if (bXjFlag) {
                        continue;
                    }
                }
                var point = new dmgis.object.Point(ScreenCoor.x, ScreenCoor.y);
                point.info = this.PointsArr[i];
                TempArr.push(point);
            }
        }
        return TempArr;
    };

    //----------------ogc wmts----------------//
    dmgis.olmap.OgcTileLayer = dmgis.olmap.OgcTileLayer ? dmgis.olmap.OgcTileLayer : {};
    dmgis.olmap.OgcTileLayer = function (dmlayerName, dmmapService, dmtileType, dmoptions) {
        var layerName = dmlayerName;
        var mapService = dmmapService;
        var tileType = dmtileType; //是否动态裁图
        var options = dmoptions ? dmoptions : {};
        var resolutions = [];
        var matrixIds = [];
        var minx = options.extent[0];
        //var miny = options.extent[1];
        var maxx = options.extent[2];
        var maxy = options.extent[3];
        var projection = options.projection ? getProjection(options.projection) : getProjection('EPSG:3857');
        var tileSize = options.tileSize ? options.tileSize : 256;
        var maxZoom = options.maxZoom ? options.maxZoom : 18;
        var minZoom = options.minZoom ? options.minZoom : 1;
        // 计算百度使用的分辨率
        for (var i = 0; i <= maxZoom; i++) {
            resolutions[i] = (maxx - minx) / Math.pow(2, i) / tileSize;
            matrixIds[i] = i;
        }
        var tilegrid = new TileGrid({
            origin: [minx, maxy], // 设置原点坐标
            resolutions: resolutions, // 设置分辨率
            tileSize: tileSize,
            minZoom: minZoom,
            maxZoom: maxZoom,
            extent: options.extent
        });
        var source = new XYZ({
            extent: options.extent,
            tileGrid: tilegrid,
            maxZoom: maxZoom,
            minZoom: minZoom,
            projection: projection,
            tileUrlFunction: function (tileCoord) {
                console.log(tileCoord);
                if (tileType) {
                    var z = tileCoord[0];
                    var y = Math.pow(2, z) - 1 - (Math.abs(tileCoord[2]) - 1);
                    var x = tileCoord[1];
                    var imgUrl =
                        mapService +
                        '/igs/ogc/tile/WMTSServer?service=WMTS' +
                        '&request=GetTile&version=1.0.0&layer=' +
                        layerName +
                        '&style=default&Format=image/png&tilematrixset=WholeWorld_CRS_84' +
                        '&TileMatrix={z}&TileRow={x}&TileCol={y}';
                    return imgUrl.replace('{z}', z).replace('{x}', x).replace('{y}', y);
                } else {
                    z = tileCoord[0];
                    y = Math.pow(2, z) - 1 - (Math.abs(tileCoord[2]) - 1);
                    x = tileCoord[1];
                    if (y > -1) {
                        imgUrl =
                            mapService +
                            '/igs/ogc/tile/WMTSServer?service=WMTS' +
                            '&request=GetTile&version=1.0.0&layer=' +
                            layerName +
                            '&style=default&Format=image/png&tilematrixset=WholeWorld_CRS_84' +
                            '&TileMatrix={z}&TileRow={y}&TileCol={x}';
                        return imgUrl.replace('{z}', z).replace('{x}', x).replace('{y}', y);
                    }
                }
            }
        });
        var dmTileLayer = new TileLayer({
            name: layerName,
            source: source,
            wrapX: true
        });
        return dmTileLayer;
    };

    //----------------地图操作基本方法----------------//
    dmgis.olmap.Tools = dmgis.olmap.Tools ? dmgis.olmap.Tools : {};
    dmgis.olmap.Tools = function (map, _extent) {
        this.map = map;
        this.dpi = 10;
        this.viewport = map.getViewport(); //地图页面元素
        this.overLayers = [];
        this.MouseState = 0; //鼠标状态默认移动
        this.MouseFlag = false; //用于判断鼠标是否停止移动
        this.snap = null; //修改类别
        this.modify = null; //修改操作类
        this.listener = null; //绘图过程中的事件监听
        this.drawSource = null; //当前绘制源
        this.measureTooltip = null; // 一个覆盖面来显示测量对象, ol类型 {ol.Overlay}
        this.measureTooltipElement = null; //测量提示对象
        this.helpTooltip = null; //  * 一个覆盖面来显示帮助对象,ol类型 {ol.Overlay}
        this.helpTooltipElement = null; //帮助提示对象
        this.draw = null; //交互操作中绘制类
        this.drawStyle = null; //绘制样式
        this.vlaystyle = null; //矢量数组对应的显示参数
        this.mapExtent = _extent; //地图显示范围
        this.modify = null; //修改操作类
        this.vectorLayers = {}; //矢量图层
        this.activeVctLayer = null; //当前激活图层
        this.sketch = null; //
        this.BindEvents();

        this.callback = null;
    };
    //事件绑定
    dmgis.olmap.Tools.prototype.BindEvents = function () {
        //_mousesstate改
        //移动事件绑定
        var dmgismap = this;
        //dmgismap.map.on("postrender", dmgismap.render, dmgismap);
        dmgismap.map.on('pointermove', dmgismap.pointerMoveHandler, this); //将地图对象传送到ol.map中
        //点击事件绑定
        //dmgismap.map.on('singleclick', dmgismap.singleClick, this); //真实单个点击
        //由于openlayer没有监听右键菜单,采用地图容器html元素类来实现操作,这里次啊用jQuery中的on方法来添加事件监听,同时也可以用off方法来关闭事件监听

        //$(this.viewport).on("contextmenu", dmgismap, dmgismap.contextmenu);改
    };

    //右键菜单重定义
    dmgis.olmap.Tools.prototype.contextmenu = function (evt) {
        var dmgismap = evt.data;
        dmgismap.MouseFlag = false;
        if (dmgismap.helpTooltipElement) {
            dmgismap.helpTooltipElement.innerHTML = '';
        }
        dmgismap.map.removeInteraction(dmgismap.draw); //移除绘制控制
        evt.preventDefault(); //屏蔽自带的右键事件
        if (dmgismap.MouseState == 9) {
            dmgismap.MouseState = -1;
            return;
        }
        var coordinate = dmgismap.map.getEventCoordinate(evt);
        var overlay = dmgismap.map.getOverlayById('menuCotent'); //id唯一,且不改变
        overlay.setPosition(coordinate);

        //$('.MapMenu', overlay.element).css("display", "block");改

        dmgismap.SwitchMouseState(0);
    };

    //添加覆盖层
    dmgis.olmap.Tools.prototype.AddOverlayer = function (overLay) {
        this.overLayers.push(overLay);
        this.map.addOverlay(overLay);
    };
    dmgis.olmap.Tools.prototype.clearAll = function () {
        //删除矢量图层数据
        for (var obj in this.vectorLayers) {
            if (!obj.includes('border')) {
                this.vectorLayers[obj].getSource().clear(true);
            }
        }
        //删除覆盖层数据
        for (var i = 0; i < this.overLayers.length; i++) {
            var overLay = this.overLayers[i];
            //避免删除右键菜单
            if (overLay.getId() !== 'menuCotent') {
                overLay.element.remove(); //有问题
            }
        }
    };
    //复位
    dmgis.olmap.Tools.prototype.Reset = function () {
        this.fitExtent(this.mapExtent);
    };
    //自适应地图范围
    dmgis.olmap.Tools.prototype.fitExtent = function (_extent) {
        if (_extent === undefined) {
            _extent = this.mapExtent;
        }
        this.map.getView().fit(_extent);
    };

    /**
     * 创建一个帮助提示
     */
    dmgis.olmap.Tools.prototype.createHelpTooltip = function () {
        if (this.helpTooltipElement) {
            this.helpTooltipElement.parentNode.removeChild(this.helpTooltipElement);
        }
        this.helpTooltipElement = document.createElement('div');
        this.helpTooltipElement.className = 'tooltip hidden';
        this.helpTooltip = new Overlay({
            element: this.helpTooltipElement,
            offset: [15, 0],
            positioning: 'center-left'
        });
        this.AddOverlayer(this.helpTooltip);
    };
    /**
     * 创建一个测量提示
     */
    dmgis.olmap.Tools.prototype.createMeasureTooltip = function () {
        if (this.measureTooltipElement) {
            this.measureTooltipElement.parentNode.removeChild(this.measureTooltipElement);
        }
        this.measureTooltipElement = document.createElement('div');
        this.measureTooltipElement.className = 'tooltip tooltip-measure';
        this.measureTooltip = new Overlay({
            element: this.measureTooltipElement,
            offset: [0, -15],
            positioning: 'bottom-center'
        });
        this.AddOverlayer(this.measureTooltip);
    };

    //移动操作
    dmgis.olmap.Tools.prototype.pointerMoveHandler = function (evt) {
        if (this.MouseState === 4 || this.MouseState === 5) {
            /** @type {string} */
            var helpMsg = '点击地图以开始绘制';

            var continuePolygonMsg = '点击地图绘制多边形';
            /**
             * Message to show when the user is drawing a line.
             * @type {string}
             */
            var continueLineMsg = '点击地图绘制线';
            if (this.sketch) {
                var geom = this.sketch.getGeometry();
                if (geom instanceof Polygon) {
                    helpMsg = continuePolygonMsg;
                } else if (geom instanceof LineString) {
                    helpMsg = continueLineMsg;
                }
            }

            this.helpTooltipElement.innerHTML = helpMsg;
            this.helpTooltip.setPosition(evt.coordinate);
            this.helpTooltipElement.classList.remove('hidden');
            this.map.getViewport().addEventListener('mouseout', function () {
                //dmgismap.helpTooltipElement.classList.add('hidden');改
            });
        }
    };

    //移动事件
    dmgis.olmap.Tools.prototype.drawstart = function (evt) {
        var dmgismap = this;
        //var e = evt.originalEvent; 改
        //鼠标停止移动
        if (!this.MouseFlag) {
            return;
        }
        switch (this.MouseState) {
            case 4:
            case 5:
                {
                    // set sketch
                    dmgismap.sketch = evt.feature;
                    /** @type {ol.Coordinate|undefined} */
                    var tooltipCoord = evt.coordinate;

                    var listener = dmgismap.sketch.getGeometry().on('change', function (evt) {
                        //改
                        console.log(listener); //改
                        var geom = evt.target;
                        var output;
                        if (geom instanceof Polygon) {
                            output = dmgismap.formatArea(geom);
                            tooltipCoord = geom.getInteriorPoint().getCoordinates();
                        } else if (geom instanceof LineString) {
                            output = dmgismap.formatLength(geom);
                            tooltipCoord = geom.getLastCoordinate();
                        }
                        dmgismap.measureTooltipElement.innerHTML = output;
                        dmgismap.measureTooltip.setPosition(tooltipCoord);
                    });
                }
                break;
            default:
                dmgismap.sketch = evt.feature;
                break;
        }
    };

    //移动结束事件
    dmgis.olmap.Tools.prototype.drawend = function (evt) {
        var dmgismap = this;
        switch (this.MouseState) {
            case 4:
            case 5:
                {
                    dmgismap = this;
                    dmgismap.measureTooltipElement.className = 'tooltip tooltip-static';
                    dmgismap.measureTooltip.setOffset([0, -7]);
                    //修改绘制的实体样式
                    dmgismap.sketch.setStyle(dmgismap.vlaystyle);
                    // unset sketch
                    dmgismap.sketch = null;
                    // unset tooltip so that a new one can be created
                    dmgismap.measureTooltipElement = null;
                    dmgismap.createMeasureTooltip();
                    //ol.Observable.unByKey(listener); //解除事件监听改
                }
                break;
            case 8:
                {
                    dmgismap = this;
                    dmgismap.sketch.setStyle(dmgismap.vlaystyle);
                    // unset sketch
                    dmgismap.sketch = null;
                    if (evt.feature) {
                        // 获取框选范围
                        var geometry = evt.feature.getGeometry();
                        var extent = geometry.getExtent();
                        this.callback(extent);
                    }
                }
                break;
            case 9:
                {
                    dmgismap = this;
                    dmgismap.sketch.setStyle(dmgismap.vlaystyle);
                    // unset sketch
                    dmgismap.sketch = null;

                    if (evt.feature) {
                        geometry = evt.feature.getGeometry();
                        extent = geometry.getExtent();
                        var cliclpnts = geometry.flatCoordinates;
                        this.callback(cliclpnts);
                    }
                }
                break;
            default:
                {
                    dmgismap.sketch.setStyle(dmgismap.vlaystyle);
                    // unset sketch
                    dmgismap.sketch = null;
                }
                break;
        }
    };

    /*
     *格式化长度输出.
     * @参数 {ol.geom.LineString} line The line.
     * @返回格式化的string类型长度.
     */
    dmgis.olmap.Tools.prototype.formatLength = function (line) {
        var length = getLength(line);
        var output;
        if (length > 100) {
            output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km';
        } else {
            output = Math.round(length * 100) / 100 + ' ' + 'm';
        }
        return output;
    };
    /*
     *格式化面积输出.
     * @参数 {ol.geom.Polygon} polygon The polygon.
     * @返回格式化的string类型面积.
     */
    dmgis.olmap.Tools.prototype.formatArea = function (polygon) {
        var area = getArea(polygon);
        var output;
        if (area > 10000) {
            output = Math.round((area / 1000000) * 100) / 100 + ' ' + 'km<sup>2</sup>';
        } else {
            output = Math.round(area * 100) / 100 + ' ' + 'm<sup>2</sup>';
        }
        return output;
    };

    //添加绘制操作,soure为添加交互的矢量图层
    dmgis.olmap.Tools.prototype.AddInteraction = function (_type, _source) {
        var dmgismap = this; //定义一个地图变量指向当前地图
        if (this.modify) {
            this.modify.setActive(false); //移除修改操作
        }
        switch (this.MouseState) {
            case 4:
            case 5:
                {
                    //area为面积
                    var type = _type === 'area' ? 'Polygon' : 'LineString';
                    //定义绘制的交互类型和相关参数
                    dmgismap.draw = new Draw({
                        source: _source,
                        type: type,
                        style: new Style({
                            fill: new Fill({
                                color: 'rgba(255, 255, 255, 0.2)'
                            }),
                            stroke: new Stroke({
                                color: 'rgba(0, 0, 0, 0.5)',
                                lineDash: [10, 10],
                                width: 2
                            }),
                            image: new Circle({
                                radius: 5,
                                stroke: new Stroke({
                                    color: 'rgba(0, 0, 0, 0.7)'
                                }),
                                fill: new Fill({
                                    color: 'rgba(255, 255, 255, 0.2)'
                                })
                            })
                        })
                    });
                    var style = new Style({
                        fill: new Fill({
                            color: 'rgba(255, 255, 255, 0.2)'
                        }),
                        stroke: new Stroke({
                            color: '#ffcc33',
                            width: 2
                        }),
                        image: new Circle({
                            radius: 7,
                            fill: new Fill({
                                color: '#ffcc33'
                            })
                        })
                    });
                    dmgismap.vlaystyle = style; //赋值
                    dmgismap.drawStyle = dmgismap.draw.style_;
                    dmgismap.activeVctLayer.setStyle(style); //激活图层
                    dmgismap.map.addInteraction(dmgismap.draw); //添加绘制类到交互操作容器中
                    //创建测量工具，这里需要再次封装
                    dmgismap.createMeasureTooltip();
                    dmgismap.createHelpTooltip();
                    //绘制开始事件
                    dmgismap.draw.on('drawstart', dmgismap.drawstart, dmgismap);
                    //绘制结束事件
                    dmgismap.draw.on('drawend', dmgismap.drawend, dmgismap);
                }
                break;
            case 6:
            case 7:
            case 9:
            case 10:
                {
                    dmgismap.map.removeInteraction(dmgismap.draw);
                    dmgismap.draw = new Draw({
                        source: _source,
                        type: _type,
                        style: dmgismap.drawStyle === null ? new Style() : dmgismap.drawStyle
                    });
                    if (dmgismap.vlaystyle !== null) {
                        dmgismap.activeVctLayer.setStyle(dmgismap.vlaystyle); //激活图层
                    }
                    dmgismap.map.addInteraction(dmgismap.draw);
                    dmgismap.snap = new SnapInteraction({
                        source: _source
                    });
                    dmgismap.map.addInteraction(dmgismap.snap);
                    //绘制开始事件
                    dmgismap.draw.on('drawstart', dmgismap.drawstart, dmgismap);
                    //绘制结束事件
                    dmgismap.draw.on('drawend', dmgismap.drawend, dmgismap);
                }
                break;
            case 8: // 形状绘制
                {
                    var value = 'Box';
                    if (value !== 'None') {
                        var geometryFunction;
                        if (value === 'Square') {
                            value = 'Circle';
                            geometryFunction = Draw.createRegularPolygon(4);
                        } else if (value === 'Box') {
                            value = 'Circle';
                            geometryFunction = Draw.createBox();
                        } else if (value === 'Star') {
                            value = 'Circle';
                            geometryFunction = function (coordinates, geometry) {
                                if (!geometry) {
                                    geometry = new Polygon(null);
                                }
                                var center = coordinates[0];
                                var last = coordinates[1];
                                var dx = center[0] - last[0];
                                var dy = center[1] - last[1];
                                var radius = Math.sqrt(dx * dx + dy * dy);
                                var rotation = Math.atan2(dy, dx);
                                var newCoordinates = [];
                                var numPoints = 12;
                                for (var i = 0; i < numPoints; ++i) {
                                    var angle = rotation + (i * 2 * Math.PI) / numPoints;
                                    var fraction = i % 2 === 0 ? 1 : 0.5;
                                    var offsetX = radius * fraction * Math.cos(angle);
                                    var offsetY = radius * fraction * Math.sin(angle);
                                    newCoordinates.push([center[0] + offsetX, center[1] + offsetY]);
                                }
                                newCoordinates.push(newCoordinates[0].slice());
                                geometry.setCoordinates([newCoordinates]);
                                return geometry;
                            };
                        }
                        dmgismap.draw = new Draw({
                            source: _source,
                            type: value,
                            style: dmgismap.drawStyle === null ? new Style() : dmgismap.drawStyle,
                            geometryFunction: geometryFunction
                        });

                        dmgismap.map.addInteraction(dmgismap.draw);
                        dmgismap.snap = new SnapInteraction({
                            source: _source
                        });
                        dmgismap.map.addInteraction(dmgismap.snap);
                        //绘制开始事件
                        dmgismap.draw.on('drawstart', dmgismap.drawstart, dmgismap);
                        //绘制结束事件
                        dmgismap.draw.on('drawend', dmgismap.drawend, dmgismap);
                    }
                }
                break;
            default:
                break;
        }
        dmgismap.MouseFlag = true;
    };

    //添加矢量绘制图层
    dmgis.olmap.Tools.prototype.AddVectorLayer = function (sourse, vectorLayer) {
        var vector = new VectorLayer({
            source: sourse,
            //设置图层的顺序 值越大图层在越上面
            zIndex: 99999
        });
        this.drawSource = sourse;
        this.vectorLayers[vectorLayer] = vector;
        this.map.addLayer(vector);
        this.activeVctLayer = vector; //设置当前激活图层
    };

    //设置激活矢量图层
    dmgis.olmap.Tools.prototype.SetActiveVecLayer = function (vector) {
        this.activeVctLayer = vector; //设置激活矢量图层
        this.drawSource = vector.getSource(); //设置当前绘制数据源
    };

    //设置鼠标状态
    dmgis.olmap.Tools.prototype.SwitchMouseState = function (state) {
        if (this.MouseFlag) {
            this.MouseFlag = !this.MouseFlag;
        }
        this.MouseState = state;
        this.SetActiveVecLayer(this.vectorLayers['vector']);
        //0:移动，1放大，2:缩小，3:无，4：测量，5:点，6：线，7：矩形：8：多边形，9:圆
        var cursorArray = [
            'dmMapSource/image/openhand.cur',
            'dmMapSource/image/ZoomIn.cur',
            'dmMapSource/image/ZoomOut.cur',
            '',
            'dmMapSource/image/ruler.cur',
            'dmMapSource/image/PointQuery.cur',
            'dmMapSource/image/LineQuery.cur',
            'dmMapSource/image/RectQuery.cur',
            'dmMapSource/image/PolygonQuery.cur',
            'dmMapSource/image/CircleQuery.cur'
        ];
        console.log(cursorArray); //改
        this.MouseFlag = false;
        if (this.helpTooltipElement) {
            this.helpTooltipElement.innerHTML = '';
        }
        this.map.removeInteraction(this.draw); //移除绘制控制
        switch (state) {
            case -1:
                {
                    //清空
                    this.clearAll();
                }
                break;
            case 3:
                {
                    //复位
                    this.Reset();
                    //改$(this.viewport).css("cursor", "url('" + cursorArray[3] + "'),default");
                }
                break;
            case 4:
                {
                    //测距离
                    this.AddInteraction('line', this.drawSource);
                    //改$(this.viewport).css("cursor", "url('" + cursorArray[4] + "'),default");
                }
                break;
            case 5:
                {
                    //侧面积
                    this.AddInteraction('area', this.drawSource);
                    //改$(this.viewport).css("cursor", "url('" + cursorArray[4] + "'),default");
                }
                break;
            case 6: //画点
                {
                    this.AddInteraction('Point', this.drawSource);
                    //改$(this.viewport).css("cursor", "url('" + cursorArray[5] + "'),default");
                }
                break;
            case 7: //线
                {
                    this.AddInteraction('LineString', this.drawSource);
                    //改$(this.viewport).css("cursor", "url('" + cursorArray[6] + "'),default");
                }
                break;
            case 8: //矩形
                {
                    this.AddInteraction('Box', this.drawSource);
                    //改$(this.viewport).css("cursor", "url('" + cursorArray[7] + "'),default");
                }
                break;
            case 9: //多边形
                {
                    this.AddInteraction('Polygon', this.drawSource);
                    //改$(this.viewport).css("cursor", "url('" + cursorArray[8] + "'),default");
                }
                break;
            case 10: //圆
                {
                    this.AddInteraction('Circle', this.drawSource);
                    //改$(this.viewport).css("cursor", "url('" + cursorArray[9] + "'),default");
                }
                break;
            default:
                {
                    //其他
                    //改$(this.viewport).css("cursor", "url('" + cursorArray[state] + "'),default");
                }
                break;
        }
    };

    //地图指北针
    dmgis.olmap.Tools.prototype.AddCompass = function () {
        var CompassHTML =
            '<div class="CompassMain"><div class="Compass">' +
            '<div class="DMap_panN" title="向上平移"></div>' +
            '<div class="DMap_panW" title="向左平移"></div>' +
            '<div class="DMap_panE" title="向右平移"></div>' +
            '<div class="DMap_panS" title="向下平移"></div>' +
            '</div></div>';
        console.log(CompassHTML); //改
        // if ($(".CompassMain", $(this.viewport)).length === 0) {
        //     $(this.viewport).append(CompassHTML);
        //     var obj = this;
        //     $(".CompassMain .DMap_panN", $(this.viewport)).click(function() {
        //         obj.moveToUp();
        //         return false;
        //     });
        //     $(".CompassMain .DMap_panW", $(this.viewport)).click(function() {
        //         obj.moveToLeft();
        //         return false;
        //     });
        //     $(".CompassMain .DMap_panE", $(this.viewport)).click(function() {
        //         obj.moveToRight();
        //         return false;
        //     });
        //     $(".CompassMain .DMap_panS", $(this.viewport)).click(function() {
        //         obj.moveToDown();
        //         return false;
        //     });
        // }
    };

    // 向左移动地图
    dmgis.olmap.Tools.prototype.moveToLeft = function () {
        var mapCenter = this.map.getView().getCenter();
        var resolution = this.map.getView().getResolution(); //当前图层分辨率,
        mapCenter[0] += resolution * this.dpi; //每次移动10个像素
        this.map.getView().setCenter(mapCenter);
        this.map.renderSync();
    };

    // 向右移动地图
    dmgis.olmap.Tools.prototype.moveToRight = function () {
        var mapCenter = this.map.getView().getCenter();
        // 让地图中心的x值减少，即可使得地图向右移动，减少的值根据效果可自由设定
        var resolution = this.map.getView().getResolution(); //当前图层分辨率,
        mapCenter[0] -= resolution * this.dpi;
        this.map.getView().setCenter(mapCenter);
        this.map.renderSync();
    };

    // 向上移动地图
    dmgis.olmap.Tools.prototype.moveToUp = function () {
        var mapCenter = this.map.getView().getCenter();
        var resolution = this.map.getView().getResolution(); //当前图层分辨率,
        mapCenter[1] -= resolution * this.dpi;
        this.map.getView().setCenter(mapCenter);
        this.map.renderSync();
    };

    // 向下移动地图
    dmgis.olmap.Tools.prototype.moveToDown = function () {
        var mapCenter = this.map.getView().getCenter();
        var resolution = this.map.getView().getResolution(); //当前图层分辨率,
        mapCenter[1] += resolution * this.dpi;
        this.map.getView().setCenter(mapCenter);
        this.map.renderSync();
    };

    // 放大地图
    dmgis.olmap.Tools.prototype.zoomIn = function () {
        // 让地图的zoom增加1，从而实现地图放大
        this.map.getView().setZoom(this.map.getView().getZoom() + 1);
    };

    // 缩小地图
    dmgis.olmap.Tools.prototype.zoomOut = function () {
        // 让地图的zoom减小1，从而实现地图缩小
        this.map.getView().setZoom(this.map.getView().getZoom() - 1);
    };
    //添加右键菜单
    dmgis.olmap.Tools.prototype.AddRightMenu = function () {
        // var meunHTML = '<ul class="MapMenu">' +
        //     '<li><a href="javascript:void(0);"><span class="bigIco"></span>放大</a></li>' +
        //     '<li><a href="javascript:void(0);"><span class="smallIco"></span>缩小</a></li>' +
        //     '<li><a href="javascript:void(0);"><span class="moveIco"></span>移动</a></li>' +
        //     '<li><a href="javascript:void(0);"><span class="pointIco"></span>复位</a></li>' +
        //     '<li><a href="javascript:void(0);"><span class="clearIco"></span>清空</a></li>' +
        //     '</ul>';
        // //添加overLay,避免二次添加;
        // if (this.map.getOverlayById("menuCotent")) {
        //     return;
        // }
        // var menu_overlay = new Overlay({
        //     id: "menuCotent",
        //     element: $(meunHTML).get(0),
        //     positioning: 'center-center'
        // });
        // this.AddOverlayer(menu_overlay);
        // var obj = this;
        // $(".MapMenu a", $(this.viewport)).eq(0).click(function() {
        //     obj.SwitchMouseState(1);
        //     obj.zoomIn();
        //     $(".MapMenu", obj.viewport).css("display", "none");
        //     return false;
        // });
        // $(".MapMenu a", $(this.viewport)).eq(1).click(function() {
        //     obj.SwitchMouseState(2);
        //     obj.zoomOut();
        //     $(".MapMenu", obj.viewport).css("display", "none");
        //     return false;
        // });
        // $(".MapMenu a", $(this.viewport)).eq(2).click(function() {
        //     obj.SwitchMouseState(0);
        //     $(".MapMenu", obj.viewport).css("display", "none");
        //     return false;
        // });
        // $(".MapMenu a", $(this.viewport)).eq(3).click(function() {
        //     obj.SwitchMouseState(3);
        //     $(".MapMenu", obj.viewport).css("display", "none");
        //     return false;
        // });
        // $(".MapMenu a", $(this.viewport)).eq(4).click(function() {
        //     obj.SwitchMouseState(-1);
        //     $(".MapMenu", obj.viewport).css("display", "none");
        //     return false;
        // });
    };

    //添加工具条
    // dmgis.olmap.Tools.prototype.AddToolMenu = function() {
    //     var that = this;
    //     var toolHtml = '<div class="tool-container">' +
    //         '<ul class="ul">' +
    //         '<a id="zoomin"><li><img class="img" alt="放大" title="放大"  src="dmMapSource/image/放大.png" /></li></a>' +
    //         '<a id="zoomout"><li><img class="img" alt="缩小" title="缩小"  src="dmMapSource/image/缩小.png"></li></a>' +
    //         '<a id="meslength"><li><img class="img" alt="测距" title="测距"  src="dmMapSource/image/测距.png"></li></a>' +
    //         '<a id="mesarea"><li><img class="img" alt="测面积" title="测面积"  src="dmMapSource/image/测面积.png"></li></a>' +
    //         '<a id="location"><li><img class="img" alt="定位" title="定位"  src="dmMapSource/image/定位.png"/></li></a>' +
    //         '<a style="display: none;" id="mapChange"><li><img class="img" alt="切换" title="切换" src="dmMapSource/image/切换.png"/></li></a>' +
    //         '<a id="tools"><li style="border-right:none;"><img class="img" alt="工具条" title="工具条" src="dmMapSource/image/工具条.png" /></li></a>' +
    //         '</ul></div>';
    //     var toolMap = ' <ul class="subtool hidden" id="mapType"> <li>基础</li><li>地形</li></ul>';
    //     if ($(".tool-container", $(this.viewport)).length === 0) {
    //         $(this.viewport).append(toolHtml);
    //         if ($("mapType", $(this.viewport)).length === 0) {
    //             $(".ol-viewport", this.mapdiv).append(toolMap); //添加地图类型切换工具
    //         }
    //         //添加鼠标悬停事件
    //         var $img = $(".tool-container a", $(this.viewport)).find("img");
    //         $img.on("mouseover", function() {
    //             $(this).attr("src", "dmMapSource/image/" + $(this).attr("title") + "1.png");
    //         });
    //         $img.on("mouseleave", function() {
    //             $(this).attr("src", "dmMapSource/image/" + $(this).attr("title") + ".png");
    //         });
    //         var dmgismap = this;

    //         $("#zoomin", $(this.viewport)).on("click", function() {
    //             dmgismap.SwitchMouseState(1);
    //             dmgismap.zoomIn();
    //         }); //放大
    //         $("#zoomout", $(this.viewport)).on("click", function() {
    //             dmgismap.SwitchMouseState(2);
    //             dmgismap.zoomOut();
    //         }); //缩小
    //         $("#meslength", $(this.viewport)).on("click", function() {
    //             dmgismap.SwitchMouseState(4);
    //         }); //测距
    //         $("#mesarea", $(this.viewport)).on("click", function() {
    //             dmgismap.SwitchMouseState(5);
    //         }); //测面积
    //         $("#location", $(this.viewport)).on("click", function() {
    //             dmgismap.SwitchMouseState(3);
    //         }); //定位
    //         $("#mapChange", $(this.viewport)).on("click", function() {
    //             if ($(".subtool", $(this.viewport)).hasClass("hidden")) {
    //                 var top = $(".tool-container").height() + $(".tool-container").get(0).offsetTop;
    //                 var left = $(".tool-container").get(0).offsetLeft + ($(this).index()) * $(".tool-container a").width();
    //                 $(".subtool", $(this.viewport)).css("top", top);
    //                 $(".subtool", $(this.viewport)).css("left", left);
    //                 $(".subtool", $(this.viewport)).removeClass("hidden");
    //             } else {
    //                 $(".subtool", $(this.viewport)).addClass("hidden");
    //             }
    //         }); //切换
    //         $("#tools", $(this.viewport)).on("click", function() { //判断是否显示
    //             if ($(this).siblings().hasClass("hidden")) {
    //                 $(this).siblings().removeClass("hidden");
    //             } else {
    //                 $(this).siblings().addClass("hidden");
    //             }
    //         });

    //     }
    // };

    //颜色转换
    dmgis.olmap.Tools.prototype.transWin32ColorToHtml = function (color) {
        var htmlColor = '#ffffff';
        color = parseInt(color);
        try {
            var r = (color & 255).toString(16);
            var g = ((color >> 8) & 255).toString(16);
            var b = ((color >> 16) & 255).toString(16);
            htmlColor =
                '#' + (r.length < 2 ? '0' + r : r) + (g.length < 2 ? '0' + g : g) + (b.length < 2 ? '0' + b : b);
        } catch (e) {
            // TODO: handle exception
            alert(e.message);
            alert(e.message);
        }
        return htmlColor;
    };

    // 加载线
    dmgis.olmap.Tools.prototype.drawLine = function (entites) {
        if (entites !== null && entites.length > 0) {
            for (var i = 0; i < entites.length; i++) {
                var coordinates = []; //先声明一维
                for (var j = 0; j < entites[i].posArr.length; j++) {
                    coordinates[j] = []; //再声明二维
                    for (var k = 0; k < 2; k += 2) {
                        coordinates[j][k] = entites[i].posArr[j].x;
                        coordinates[j][k + 1] = entites[i].posArr[j].y;
                    }
                }
                //声明一个新的数组
                var coordinatesPolygon = [];
                //循环遍历将经纬度转到"EPSG:3857"投影坐标系下
                for (var t = 0; t < coordinates.length; t++) {
                    var pointTransform = transform([coordinates[t][0], coordinates[t][1]], 'EPSG:4326', 'EPSG:3857');
                    coordinatesPolygon.push(pointTransform);
                }
                var source = new VectorSource();
                var geom = new LineString(coordinatesPolygon);
                //多边形要素类
                var feature = new Feature({
                    geometry: geom,
                    ROADNAME: entites[i].ROADNAME,
                    PAVEMENT: entites[i].PAVEMENT,
                    MATERIAL: entites[i].MATERIAL
                });
                var lineStyle = new Style({
                    stroke: new Stroke({
                        color: this.transWin32ColorToHtml(entites[i].color == undefined ? 65535 : entites[i].color), //.replace(/\"/g, "'"),
                        width: 2
                    })
                });
                feature.setStyle(lineStyle);
                source.addFeature(feature);
                this.AddVectorLayer(source, 'Traline' + i);
            }
        }
        //this.fitExtent();
    };

    dmgis.olmap.Tools.prototype.ContainsPoint = function (polygon, pointX, pointY) {
        let n = polygon.length >> 1;

        let ax, lup;
        let ay = polygon[2 * n - 3] - pointY;
        let bx = polygon[2 * n - 2] - pointX;
        let by = polygon[2 * n - 1] - pointY;

        if (bx === 0 && by === 0) return false; // point on edge

        // let lup = by > ay;
        for (let ii = 0; ii < n; ii++) {
            ax = bx;
            ay = by;
            bx = polygon[2 * ii] - pointX;
            by = polygon[2 * ii + 1] - pointY;
            if (bx === 0 && by === 0) return false; // point on edge
            if (ay === by) continue;
            lup = by > ay;
        }

        let depth = 0;
        for (let i = 0; i < n; i++) {
            ax = bx;
            ay = by;
            bx = polygon[2 * i] - pointX;
            by = polygon[2 * i + 1] - pointY;
            if (ay < 0 && by < 0) continue; // both 'up' or both 'down'
            if (ay > 0 && by > 0) continue; // both 'up' or both 'down'
            if (ax < 0 && bx < 0) continue; // both points on the left

            if (ay === by && Math.min(ax, bx) < 0) return true;
            if (ay === by) continue;

            let lx = ax + ((bx - ax) * -ay) / (by - ay);
            if (lx === 0) return false; // point on edge
            if (lx > 0) depth++;
            if (ay === 0 && lup && by > ay) depth--; // hit vertex, both up
            if (ay === 0 && !lup && by < ay) depth--; // hit vertex, both down
            lup = by > ay;
        }
        return (depth & 1) === 1;
    };

    dmgis.olmap.Tools.prototype.pointInRect = function (rect, pointX, pointY) {
        let a = (rect[0] - rect[0]) * (pointY - rect[1]) - (rect[3] - rect[1]) * (pointX - rect[0]);
        let b = (rect[2] - rect[0]) * (pointY - rect[3]) - (rect[3] - rect[3]) * (pointX - rect[0]);
        let c = (rect[2] - rect[2]) * (pointY - rect[3]) - (rect[1] - rect[3]) * (pointX - rect[2]);
        let d = (rect[0] - rect[2]) * (pointY - rect[1]) - (rect[1] - rect[1]) * (pointX - rect[2]);
        return (a > 0 && b > 0 && c > 0 && d > 0) || (a < 0 && b < 0 && c < 0 && d < 0);
    };
})(dmgis);

//xml转对象
function parseXMLToObjectArray(xmlString) {
    // 创建一个 DOMParser 实例
    const parser = new DOMParser();
    // 将 XML 字符串解析为 DOM 文档
    const xmlDoc = parser.parseFromString(xmlString, 'application/xml');

    // 检查是否有解析错误
    const parserError = xmlDoc.getElementsByTagName('parsererror');
    if (parserError.length > 0) {
        throw new Error('XML 解析错误');
    }

    // 递归函数，用于将 XML 节点转换为对象
    function nodeToObject(node) {
        const result = {};
        if (node.nodeType === Node.ELEMENT_NODE) {
            // 获取节点的属性
            const attrs = node.attributes;
            for (let i = 0; i < attrs.length; i++) {
                const attr = attrs.item(i);
                result[attr.name] = attr.value;
            }

            // 获取子节点
            const children = node.childNodes;
            for (let i = 0; i < children.length; i++) {
                const child = children.item(i);
                if (child.nodeType === Node.ELEMENT_NODE) {
                    const childName = child.nodeName;
                    if (childName in result) {
                        // 如果已经有同名属性，将其转换为数组
                        if (!Array.isArray(result[childName])) {
                            result[childName] = [result[childName]];
                        }
                        result[childName].push(nodeToObject(child));
                    } else {
                        result[childName] = nodeToObject(child);
                    }
                }
            }
        } else if (node.nodeType === Node.TEXT_NODE) {
            result.value = node.nodeValue.trim();
        }
        return result;
    }

    // 获取 DMGISXML 标签内的内容
    const dmgisXmlNode = xmlDoc.getElementsByTagName('DMGISXML')[0];
    if (!dmgisXmlNode) {
        throw new Error('未找到 DMGISXML 标签');
    }

    return nodeToObject(dmgisXmlNode);
}

let data = {
    name: 'DMGISXML',
    version: '1.1',
    children: {
        name: 'REQUEST',
        children: {
            name: 'GET_FEATURES',
            attributes: {
                attributes: '1',
                beginrecord: '0',
                envelope: '1',
                featurelimit: '1000',
                geometry: '1',
                globalenvelope: '1',
                layername: '省界_region',
                nodflag: '0'
            },
            children: {
                name: 'GETOBJ',
                type: '0',
                children: {
                    name: 'SPATIALQUERY',
                    children: {
                        name: 'QUERY',
                        singleLabel: true
                    }
                }
            }
        }
    }
};
// 示例对象
const exampleObjectWithArray = {
    name: 'ROOT',
    children: [
        {
            name: 'ITEM',
            attributes: {
                id: '1',
                type: 'A'
            },
            children: {
                name: 'DETAIL',
                children: {
                    name: 'NAME',
                    singleLabel: true,
                    value: 'Item 1'
                }
            }
        },
        {
            name: 'ITEM',
            attributes: {
                id: '2',
                type: 'B'
            },
            children: {
                name: 'DETAIL',
                children: {
                    name: 'NAME',
                    singleLabel: true,
                    value: 'Item 2'
                }
            }
        }
    ]
};

//对象转xml
function objectToXML(obj) {
    let xml = [];

    function buildXML(node) {
        const name = node.name;
        let attributes;
        if (node.attributes) {
            attributes = Object.entries(node.attributes)
                .map(([key, value]) => `${key}="${value}"`)
                .join(' ');
        } else {
            attributes = '';
        }
        const value = node.value ? `${node.value}` : '';

        if (node.singleLabel) {
            // 单标签，自闭合
            xml.push(`<${name} ${attributes} ${value ? `value="${value}"` : ''} />`);
        } else {
            // 非单标签，开始标签
            xml.push(`<${name} ${attributes}>${value}`);
            if (node.children) {
                if (typeof node.children === 'object' && !Array.isArray(node.children)) {
                    buildXML(node.children);
                } else if (Array.isArray(node.children)) {
                    node.children.forEach((child) => buildXML(child));
                }
            }
            // 结束标签
            xml.push(`</${name}>`);
        }
    }

    buildXML(obj);
    return xml.join('');
}
// console.log(objectToXML(exampleObjectWithArray));
// console.log(objectToXML(data));

export default dmgis;
